溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

JavaScript日期工具類DateUtils定義與用法示例

發(fā)布時間:2020-10-13 08:13:34 來源:腳本之家 閱讀:155 作者:老鼠擰刀滿街找貓 欄目:web開發(fā)

本文實例講述了JavaScript日期工具類DateUtils定義與用法。分享給大家供大家參考,具體如下:

DateUtils = {
  patterns: {
   PATTERN_ERA: 'G', //Era 標(biāo)志符 Era strings. For example: "AD" and "BC"
   PATTERN_YEAR: 'y', //年
   PATTERN_MONTH: 'M', //月份
   PATTERN_DAY_OF_MONTH: 'd', //月份的天數(shù)
   PATTERN_HOUR_OF_DAY1: 'k', //一天中的小時數(shù)(1-24)
   PATTERN_HOUR_OF_DAY0: 'H', //24小時制,一天中的小時數(shù)(0-23)
   PATTERN_MINUTE: 'm', //小時中的分鐘數(shù)
   PATTERN_SECOND: 's', //秒
   PATTERN_MILLISECOND: 'S', //毫秒
   PATTERN_DAY_OF_WEEK: 'E', //一周中對應(yīng)的星期,如星期一,周一
   PATTERN_DAY_OF_YEAR: 'D', //一年中的第幾天
   PATTERN_DAY_OF_WEEK_IN_MONTH: 'F', //一月中的第幾個星期(會把這個月總共過的天數(shù)除以7,不夠準(zhǔn)確,推薦用W)
   PATTERN_WEEK_OF_YEAR: 'w', //一年中的第幾個星期
   PATTERN_WEEK_OF_MONTH: 'W', //一月中的第幾星期(會根據(jù)實際情況來算)
   PATTERN_AM_PM: 'a', //上下午標(biāo)識
   PATTERN_HOUR1: 'h', //12小時制 ,am/pm 中的小時數(shù)(1-12)
   PATTERN_HOUR0: 'K', //和h類型
   PATTERN_ZONE_NAME: 'z', //時區(qū)名
   PATTERN_ZONE_VALUE: 'Z', //時區(qū)值
   PATTERN_WEEK_YEAR: 'Y', //和y類型
   PATTERN_ISO_DAY_OF_WEEK: 'u',
   PATTERN_ISO_ZONE: 'X'
  },
  week: {
   'ch': {
    "0": "\u65e5",
    "1": "\u4e00",
    "2": "\u4e8c",
    "3": "\u4e09",
    "4": "\u56db",
    "5": "\u4e94",
    "6": "\u516d"
   },
   'en': {
    "0": "Sunday",
    "1": "Monday",
    "2": "Tuesday",
    "3": "Wednesday",
    "4": "Thursday",
    "5": "Friday",
    "6": "Saturday"
   }
  },
  //獲取當(dāng)前時間
  getCurrentTime: function() {
   var today = new Date();
   var year = today.getFullYear();
   var month = today.getMonth() + 1;
   var day = today.getDate();
   var hours = today.getHours();
   var minutes = today.getMinutes();
   var seconds = today.getSeconds();
   var timeString = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
   return timeString;
  },
  /*
   * 比較時間大小
   * time1>time2 return 1
   * time1<time2 return -1
   * time1==time2 return 0
   */
  compareTime: function(time1, time2) {
   if(Date.parse(time1.replace(/-/g, "/")) > Date.parse(time2.replace(/-/g, "/"))) {
    return 1;
   } else if(Date.parse(time1.replace(/-/g, "/")) < Date.parse(time2.replace(/-/g, "/"))) {
    return -1;
   } else if(Date.parse(time1.replace(/-/g, "/")) == Date.parse(time2.replace(/-/g, "/"))) {
    return 0;
   }
  },
  //是否閏年
  isLeapYear: function(year) {
   return((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);
  },
  //獲取某個月的天數(shù),從0開始
  getDaysOfMonth: function(year, month) {
   return [31, (this.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
  },
  getDaysOfMonth3: function(year, month) {
   // 將天置為0,會獲取其上個月的最后一天
   month = parseInt(month) + 1;
   var date = new Date(year, month, 0);
   return date.getDate();
  },
  /*距離現(xiàn)在幾天的日期:負數(shù)表示今天之前的日期,0表示今天,整數(shù)表示未來的日期
   * 如-1表示昨天的日期,0表示今天,2表示后天
   */
  fromToday: function(days) {
   var today = new Date();
   today.setDate(today.getDate() + days);
   var date = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate();
   return date;
  },
  /**
   * 日期時間格式化
   * @param {Object} dateTime 需要格式化的日期時間
   * @param {String} pattern 格式化的模式,如yyyy-MM-dd hh(HH):mm:ss.S a k K E D F w W z Z
   */
  formt: function(dateTime, pattern) {
   var date = new Date(dateTime);
   if(Bee.StringUtils.isBlank(pattern)) {
    return date.toLocaleString();
   }
   return pattern.replace(/([a-z])\1*/ig, function(matchStr, group1) {
    var replacement = "";
    switch(group1) {
     case Bee.DateUtils.patterns.PATTERN_ERA: //G
      break;
     case Bee.DateUtils.patterns.PATTERN_WEEK_YEAR: //Y
     case Bee.DateUtils.patterns.PATTERN_YEAR: //y
      replacement = date.getFullYear();
      break;
     case Bee.DateUtils.patterns.PATTERN_MONTH: //M
      var month = date.getMonth() + 1;
      replacement = (month < 10 && matchStr.length >= 2) ? "0" + month : month;
      break;
     case Bee.DateUtils.patterns.PATTERN_DAY_OF_MONTH: //d
      var days = date.getDate();
      replacement = (days < 10 && matchStr.length >= 2) ? "0" + days : days;
      break;
     case Bee.DateUtils.patterns.PATTERN_HOUR_OF_DAY1: //k(1~24)
      var hours24 = date.getHours();
      replacement = hours24;
      break;
     case Bee.DateUtils.patterns.PATTERN_HOUR_OF_DAY0: //H(0~23)
      var hours24 = date.getHours();
      replacement = (hours24 < 10 && matchStr.length >= 2) ? "0" + hours24 : hours24;
      break;
     case Bee.DateUtils.patterns.PATTERN_MINUTE: //m
      var minutes = date.getMinutes();
      replacement = (minutes < 10 && matchStr.length >= 2) ? "0" + minutes : minutes;
      break;
     case Bee.DateUtils.patterns.PATTERN_SECOND: //s
      var seconds = date.getSeconds();
      replacement = (seconds < 10 && matchStr.length >= 2) ? "0" + seconds : seconds;
      break;
     case Bee.DateUtils.patterns.PATTERN_MILLISECOND: //S
      var milliSeconds = date.getMilliseconds();
      replacement = milliSeconds;
      break;
     case Bee.DateUtils.patterns.PATTERN_DAY_OF_WEEK: //E
      var day = date.getDay();
      replacement = Bee.DateUtils.week['ch'][day];
      break;
     case Bee.DateUtils.patterns.PATTERN_DAY_OF_YEAR: //D
      replacement = Bee.DateUtils.dayOfTheYear(date);
      break;
     case Bee.DateUtils.patterns.PATTERN_DAY_OF_WEEK_IN_MONTH: //F
      var days = date.getDate();
      replacement = Math.floor(days / 7);
      break;
     case Bee.DateUtils.patterns.PATTERN_WEEK_OF_YEAR: //w
      var days = Bee.DateUtils.dayOfTheYear(date);
      replacement = Math.ceil(days / 7);
      break;
     case Bee.DateUtils.patterns.PATTERN_WEEK_OF_MONTH: //W
      var days = date.getDate();
      replacement = Math.ceil(days / 7);
      break;
     case Bee.DateUtils.patterns.PATTERN_AM_PM: //a
      var hours24 = date.getHours();
      replacement = hours24 < 12 ? "\u4e0a\u5348" : "\u4e0b\u5348";
      break;
     case Bee.DateUtils.patterns.PATTERN_HOUR1: //h(1~12)
      var hours12 = date.getHours() % 12 || 12; //0轉(zhuǎn)為12
      replacement = (hours12 < 10 && matchStr.length >= 2) ? "0" + hours12 : hours12;
      break;
     case Bee.DateUtils.patterns.PATTERN_HOUR0: //K(0~11)
      var hours12 = date.getHours() % 12;
      replacement = hours12;
      break;
     case Bee.DateUtils.patterns.PATTERN_ZONE_NAME: //z
      replacement = Bee.DateUtils.getZoneNameValue(date)['name'];
      break;
     case Bee.DateUtils.patterns.PATTERN_ZONE_VALUE: //Z
      replacement = Bee.DateUtils.getZoneNameValue(date)['value'];
      break;
     case Bee.DateUtils.patterns.PATTERN_ISO_DAY_OF_WEEK: //u
      break;
     case Bee.DateUtils.patterns.PATTERN_ISO_ZONE: //X
      break;
     default:
      break;
    }
    return replacement;
   });
  },
  /**
   * 計算一個日期是當(dāng)年的第幾天
   * @param {Object} date
   */
  dayOfTheYear: function(date) {
   var obj = new Date(date);
   var year = obj.getFullYear();
   var month = obj.getMonth(); //從0開始
   var days = obj.getDate();
   var daysArr = [31, (this.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
   for(var i = 0; i < month; i++) {
    days += daysArr[i];
   }
   return days;
  },
  //獲得時區(qū)名和值
  getZoneNameValue: function(dateObj) {
   var date = new Date(dateObj);
   date = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
   var arr = date.toString().match(/([A-Z]+)([-+]\d+:?\d+)/);
   var obj = {
    'name': arr[1],
    'value': arr[2]
   };
   return obj;
  }
};
//用法示例
console.log(DateUtils.getCurrentTime())//獲取當(dāng)前時間
console.log(DateUtils.compareTime('2018-8-1','2018-9-3'))//比較時間
console.log(DateUtils.isLeapYear('2018'))//是否閏年
console.log(DateUtils.getDaysOfMonth('2018','9'))//獲取指定月份的天數(shù)(從0計數(shù))
console.log(DateUtils.dayOfTheYear('2018-9-3'))//計算指定日期是當(dāng)年第幾天

使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun測試運行結(jié)果如下:

JavaScript日期工具類DateUtils定義與用法示例

PS:這里再為大家推薦幾款比較實用的天數(shù)計算在線工具供大家使用:

在線日期/天數(shù)計算器:
http://tools.jb51.net/jisuanqi/date_jisuanqi

在線日期計算器/相差天數(shù)計算器:
http://tools.jb51.net/jisuanqi/datecalc

在線日期天數(shù)差計算器:
http://tools.jb51.net/jisuanqi/onlinedatejsq

在線天數(shù)計算器:
http://tools.jb51.net/jisuanqi/datejsq

更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《JavaScript時間與日期操作技巧總結(jié)》、《JavaScript+HTML5特效與技巧匯總》、《JavaScript錯誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》及《JavaScript數(shù)學(xué)運算用法總結(jié)》

希望本文所述對大家JavaScript程序設(shè)計有所幫助。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI