JS時間類擴展

日期格式化

/**
 * 日期對象擴展(日期格式化)
 * @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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章