JS时间类扩展

来源:互联网 发布:什么是多媒体集成软件 编辑:程序博客网 时间:2024/06/05 15:06

日期格式化

/** * 日期对象扩展(日期格式化) * @param fmt  (yyyy-MM-dd hh:mm:ss.S) * @returns */Date.prototype.format = function(fmt)   {   var o = {       "M+" : this.getMonth()+1,                 //月份       "d+" : this.getDate(),                    //日       "h+" : this.getHours(),                   //小时       "m+" : this.getMinutes(),                 //分       "s+" : this.getSeconds(),                 //秒       "q+" : Math.floor((this.getMonth()+3)/3), //季度       "S"  : this.getMilliseconds()             //毫秒     };     if(/(y+)/.test(fmt))       fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));     for(var k in o)       if(new RegExp("("+ k +")").test(fmt))     fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));     return fmt;   }  

使用实例
new Date().format("yyyy-MM-dd hh")
//prints 2016-06-23 14
new Date().format("yyyy-MM-dd hh:mm:ss.S")
//prints 2016-06-23 14:32:08.632


时间比较,返回指定单位的数值

/** * 时间比较 * @param strInterval 需要返回的单位 * @param dtEnd 比较的时间 * @returns */Date.prototype.DateDiff = function(strInterval, dtEnd) {       var dtStart = this;      if (typeof dtEnd == 'string' )//如果是字符串转换为日期型      {           dtEnd = new Date(dtEnd);      }      switch (strInterval) {           case 's' :return parseInt((dtEnd - dtStart) / 1000);  //秒        case 'm' :return parseInt((dtEnd - dtStart) / 60000);  //分        case 'h' :return parseInt((dtEnd - dtStart) / 3600000);  //时        case 'd' :return parseInt((dtEnd - dtStart) / 86400000);  //日        case 'w' :return parseInt((dtEnd - dtStart) / (86400000 * 7));  //周        case 'M' :return (dtEnd.getMonth()+1)+((dtEnd.getFullYear()-dtStart.getFullYear())*12) - (dtStart.getMonth()+1);  //月        case 'y' :return dtEnd.getFullYear() - dtStart.getFullYear();  //年    }  }  

使用实例
new Date('2016-06-23').DateDiff("s",'2016-06-24') //返回相差的秒数
//prints 86400
new Date('2016-06-23').DateDiff("d",'2016-06-24') //返回相差的天数
//prints 1


0 0
原创粉丝点击