javascript Date对象追加函数: Format clone addDays addWeeks addMonths addYears
1 //js格式化时间 "yyyy-MM-dd hh:mm:ss" 2 Date.prototype.Format = function (fmt) { 3 var o = { 4 "M+": this.getMonth() + 1, //月份 5 "d+": this.getDate(), //日 6 "h+": this.getHours(), //小时 7 "m+": this.getMinutes(), //分 8 "s+": this.getSeconds(), //秒 9 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 10 "S": this.getMilliseconds() //毫秒 11 }; 12 if (/(y+)/.test(fmt)) 13 fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); 14 for (var k in o) 15 if (new RegExp("(" + k + ")").test(fmt)) 16 fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); 17 return fmt; 18 } 19 Date.prototype.clone = function () { 20 return new Date(this.valueOf()); 21 } 22 Date.prototype.addDays = function (d) { 23 this.setDate(this.getDate() + d); 24 }; 25 Date.prototype.addWeeks = function (w) { 26 this.addDays(w * 7); 27 }; 28 Date.prototype.addMonths = function (m) { 29 var d = this.getDate(); 30 this.setMonth(this.getMonth() + m); 31 if (this.getDate() < d) 32 this.setDate(0); 33 }; 34 Date.prototype.addYears = function (y) { 35 var m = this.getMonth(); 36 this.setFullYear(this.getFullYear() + y); 37 if (m < this.getMonth()) { 38 this.setDate(0); 39 } 40 };
使用范例:
var firstDayOfYear = new Date(2020, 0, 1);//元旦 var day = firstDayOfYear.clone();//js中Date对象直接赋值是拷贝引用,所以需要用我们追加的自定义克隆 day.addDays(7);//加7天 console.log(day.Format("yyyy/MM/dd"));//输出 2020/1/8