文章评分 次,平均分 :
js格式化日期
/** * 给Date的原型添加格式化时间的方法 * @param {Object} format 要格式化的类型 * @param {Object} daynum 要加减的时间的天数,加时间填正整数,减时间填负整数 * @memberOf {TypeName} * @return {TypeName} 格式化以后的时间 */ Date.prototype.format = function(format,daynum) { /* * eg:format="YYYY-MM-dd hh:mm:ss"; */ if(daynum){ this.setDate(this.getDate()+daynum); } var o = { "M+" : this.getMonth() + 1, // month "d+" : this.getDate(), // day "h+" : this.getHours(), // hour "m+" : this.getMinutes(), // minute "s+" : this.getSeconds(), // second "q+" : Math.floor((this.getMonth() + 3) / 3), // quarter "S" : this.getMilliseconds() // millisecond } if (/(Y+)/.test(format)) { format = format.replace(RegExp.$1, (this.getFullYear() + "") .substr(4 - (RegExp.$1).length)); } for ( var k in o) { if (new RegExp("(" + k + ")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); } } return format; } //test document.write(new Date().format("YYYY-MM-dd"));
js加减天数,月,年,周
/** * 给Date的原型添加天数运算的方法 * @param {Object} num 要加减的时间的数量,加时间填正整数,减时间填负整数 */ Date.prototype.opDays = function(num) { this.setDate(this.getDate() + num); return this; }; /** * 给Date的原型添加周运算的方法 * @param {Object} num 要加减的时间的数量,加时间填正整数,减时间填负整数 */ Date.prototype.opWeeks = function(num) { this.opDays(num * 7); return this; }; /** * 给Date的原型添加月运算的方法 * @param {Object} num 要加减的时间的数量,加时间填正整数,减时间填负整数 */ Date.prototype.opMonths= function(num) { var d = this.getDate(); this.setMonth(this.getMonth() + num); return this; }; /** * 给Date的原型添加年运算的方法 * @param {Object} num 要加减的时间的数量,加时间填正整数,减时间填负整数 */ Date.prototype.opYears = function(num) { var m = this.getMonth(); this.setFullYear(this.getFullYear() +num); return this; } document.write(new Date().format("YYYY-MM-dd")+"</br>");//当前日期减去7天,并格式化 document.write(new Date().opWeeks(-1).format("YYYY-MM-dd")+"</br>");//当前日期减去一周,并格式化 document.write(new Date().opMonths(5).format("YYYY-MM-dd")+"</br>");//当前日期减去5月,并格式化 document.write(new Date().opYears(-1).format("YYYY-MM-dd")+"</br>");//当前日期减去一年,并格式化
除特别注明外,本站所有文章均为我要编程原创,转载请注明出处来自http://5ycode.com/article/291.html