js格式化日期 js加减日期 js时间运算

2013/10/16 2881点热度 0人点赞 0条评论

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>");//当前日期减去一年,并格式化

yxkong

这个人很懒,什么都没留下

文章评论