<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          幾個(gè)JavaScript極短日期時(shí)間代碼片段(你值得擁有)

          共 19037字,需瀏覽 39分鐘

           ·

          2021-09-16 22:11

          點(diǎn)擊上方 前端瓶子君,關(guān)注公眾號(hào)

          回復(fù)算法,加入前端編程面試算法每日一題群

          前言

          本篇文章主打極短的日期時(shí)間相關(guān)代碼片段,讓你不用工具庫也能秀的飛起

          1.是否今天

          日期是不是今天,我們只需要判斷 日期的 年月日 是否與 當(dāng)前日期的 年月日一致即可,所以我們的常規(guī)代碼片段如下:

          function isToday(dt = new Date()) {
              let curDate = new Date() // 當(dāng)前日期 
              let comparedDate= new Date(typeof dt === 'string'&&dt.includes('-')?dt.replace(/-/g,'/'):dt) // 傳入日期
              return curDate.getFullYear() === comparedDate.getFullYear() && // 年相等
                     curDate.getMonth() === comparedDate.getMonth() && // 月相等
                     curDate.getDate() === comparedDate.getDate() // 日相等
          }
          復(fù)制代碼

          我知道有小伙伴會(huì)說,“就這...!極短???”,別急,別急,請(qǐng)你繼續(xù)往下看

          isToday極短代碼片段如下

          // isToday 極短代碼片段
          const isToday =  (dt = new Date())=>['getFullYear''getMonth''getDate'].every(i => new Date()[i]() === new Date(typeof dt === 'string'&&dt.includes('-')?dt.replace(/-/g,'/'):dt)[i]())
          復(fù)制代碼

          使用了提取公因式,把 重復(fù)出現(xiàn)的 getFullYear, getMonth,getDate 給提取出來用every結(jié)合而成

          2.是否昨天

          是否昨天,我們只需把當(dāng)前日期減一天,再做比較即可,所以我們的常規(guī)代碼片段如下:

          function isYesterday(dt = new Date()) {
              let curDate = new Date() // 當(dāng)前日期 
              curDate.setDate( curDate.getDate() - 1 ) // 當(dāng)前日期減一天
              let comparedDate= new Date(typeof dt === 'string'&&dt.includes('-')?dt.replace(/-/g,'/'):dt) // 傳入日期
              return curDate.getFullYear() === comparedDate.getFullYear() && // 年相等
                     curDate.getMonth() === comparedDate.getMonth() && // 月相等
                     curDate.getDate() === comparedDate.getDate() // 日相等
          }
          復(fù)制代碼

          是否昨天極短代碼片段的實(shí)現(xiàn)大致和是否今天一樣,不同的是,首先要定義出昨天具體是哪一天的標(biāo)準(zhǔn),才能使用傳入的日期和標(biāo)準(zhǔn)日期做比較,我們具體操作 是 當(dāng)前時(shí)間戳 減去一天的時(shí)間戳即new Date() \- 24*60*60*1000,得到一個(gè)昨天的標(biāo)準(zhǔn)日期時(shí)間戳,然后再做比較

          // isYesterday 極短代碼片段
          const isYesterday =(dt = new Date())=>['getFullYear''getMonth''getDate'].every(i => new Date(new Date() - 24*60*60*1000)[i]() === new Date(typeof dt === 'string'&&dt.includes('-')?dt.replace(/-/g,'/'):dt)[i]())
          復(fù)制代碼

          3.是否明天

          是否明天,我們只需把當(dāng)前日期加一天,再做比較即可,所以我們的常規(guī)代碼片段如下:

          function isTomorrow(dt = new Date()) {
              let curDate = new Date() // 當(dāng)前日期 
              curDate.setDate( curDate.getDate() + 1 ) // 當(dāng)前日期加一天
              let comparedDate= new Date(typeof dt === 'string'&&dt.includes('-')?dt.replace(/-/g,'/'):dt) // 傳入日期
              return curDate.getFullYear() === comparedDate.getFullYear() && // 年相等
                     curDate.getMonth() === comparedDate.getMonth() && // 月相等
                     curDate.getDate() === comparedDate.getDate() // 日相等
          }
          復(fù)制代碼

          是否明天極短代碼片段的實(shí)現(xiàn)和是否昨天相反,是 當(dāng)前時(shí)間戳 加上一天的時(shí)間戳即+new Date() + 24*60*60*1000,得到一個(gè)昨天的標(biāo)準(zhǔn)日期時(shí)間戳,然后再做比較

          // isTomorrow 極短代碼片段
          const isTomorrow = (dt = new Date())=>['getFullYear''getMonth''getDate'].every(i => new Date(+new Date() + 86400000)[i]() === new Date(typeof dt === 'string'&&dt.includes('-')?dt.replace(/-/g,'/'):dt)[i]())
          復(fù)制代碼

          4.月天數(shù)

          關(guān)于月天數(shù)需求,我們大致有:

          • 獲取當(dāng)前日期所屬月份天數(shù),簡(jiǎn)稱獲取當(dāng)月天數(shù)
          • 獲取當(dāng)前日期所在年中的任一月份天數(shù),簡(jiǎn)稱獲取今年任一月天數(shù)
          • 獲取給定日期所屬月份天數(shù),簡(jiǎn)稱獲取指定日期的所屬月天數(shù)
          • 獲取給定日期所在年中任一月天數(shù),簡(jiǎn)稱獲取指定日期的所屬年任一月天數(shù)
          • 獲取年任一月天數(shù)

          我們方法需要兩個(gè)參數(shù)來完成這個(gè)功能函數(shù),所以我們的常規(guī)代碼片段是:

          function daysInMonth(month = new Date().getMonth() + 1, dt = new Date()) {
              let is = month >= 1 && month <= 12
              dt = is ? dt : month
              month = is ? month : new Date(month).getMonth() + 1
              //解析傳入的日期 dt
              const d = new Date(typeof dt === 'string' && dt.includes('-') ? dt.replace(/-/g'/') : dt.toString())
              // 設(shè)置月份
              d.setMonth(month) // 因?yàn)樵路菔前此饕?nbsp;0-11,索引這里沒有進(jìn)行 - 1
              // 設(shè)置日期為0,那么日期就會(huì)被設(shè)置為上個(gè)月的最后一天
              d.setDate(0)
              // 返回上月最后一天日期,因?yàn)樵路菔前此饕?nbsp;0-11
              return d.getDate()
          }
          復(fù)制代碼

          具體使用:

          // 獲取當(dāng)前月份天數(shù)  -- 獲取當(dāng)月天數(shù)
          daysInMonth()
          // 獲取今年2月份天數(shù) -- 獲取今年任一月天數(shù)
          daysInMonth(2)
          // 獲取2000年2月份天數(shù)
          daysInMonth(22000)
          // 獲取指定時(shí)間(2000-01-01 12:23:59)指定月份(2)的天數(shù) -- 獲取指定日期的所屬年任一月天數(shù)
          daysInMonth(2'2000-01-01 12:23:59')
          // 獲取指定時(shí)間(2000-01-01 12:23:59)所屬月天數(shù)   -- 獲取指定日期的所屬月天數(shù)
          daysInMonth('2000-01-01 12:23:59')
          復(fù)制代碼

          setDate(0)那么日期就會(huì)被設(shè)置為上個(gè)月的最后一天,具體更多可以看 MDN Date.prototype.setDate[1]的描述

          月天數(shù)如何個(gè)極短法呢,可讀性可能要犧牲點(diǎn)了,不過也還好,借助new Date(year,month,0).getDate()進(jìn)行實(shí)現(xiàn),具體如下:

          const daysInMonth = function (month = new Date().getMonth() + 1, dt = new Date()) {
              let is = month >= 1 && month <= 12
              dt = is ? dt : month
              month = is ? month : new Date(month).getMonth() + 1
              let date = new Date(typeof dt === 'string' && dt.includes('-') ? dt.replace(/-/g'/') : dt.toString())
              const year = date.getFullYear()
              return new Date(year, month, 0).getDate()
          }
          復(fù)制代碼

          這個(gè)還真優(yōu)化不了什么,同時(shí)又需兼具有以上5個(gè)需求使用特征,麻雀雖小,但五臟俱全

          5. 格式化

          在前端項(xiàng)目中,使用日期時(shí)間相關(guān)的方法,格式化方法頻率比較高,那么我們自己實(shí)現(xiàn)一個(gè) format方法吧,在實(shí)現(xiàn)之前 依然保留傳統(tǒng)的使用方法,因?yàn)闆]有我們是單個(gè)方法,實(shí)現(xiàn)單兵作戰(zhàn)高效強(qiáng)悍,實(shí)現(xiàn)的時(shí)候有些地方我們會(huì)做些改變,具體哪些改變請(qǐng)往下看

          /**
           * @description: 日期時(shí)間格式化函數(shù)
           * @param  { Array } args :形參數(shù)組,生效的最多為前兩個(gè)參數(shù)
           * 1個(gè)參數(shù)情況:
           *      1.1 參數(shù)為格式,則默認(rèn)格式化當(dāng)前時(shí)間
           *      1.2 參數(shù)為時(shí)間戳或字符串時(shí)間,則使用默認(rèn)格式去格式化化給定的 時(shí)間戳或字符串時(shí)間
           * 2個(gè)參數(shù)情況:
           * 第一個(gè)參數(shù)表示格式化的日期,可以是時(shí)間戳或字符串時(shí)間
           * 第二個(gè)參數(shù)表示格式
           */

          const format = function (...args{
              try {
                  // 參數(shù)解構(gòu)
                  const [a, b] = args
                  // 默認(rèn)值
                  let dt = new Date(), //默認(rèn)當(dāng)前時(shí)間
                      ft = 'YYYY-MM-DD HH:mm:ss' // 默認(rèn)格式
                  //如果參數(shù)只傳入了一個(gè)的情況,我們認(rèn)為用戶用戶傳入的是格式,需要格式化的是當(dāng)前時(shí)間
                  if (args.length == 1) {
                      if (isNaN(new Date(a).valueOf())) {
                          ft = a
                      } else {
                          dt = new Date(typeof a == 'string' && a.includes('-') ? a.replace(/-/g'/') : a)
                      }
                  } else if (args.length >= 2) {
                      dt = new Date(typeof a == 'string' && a.includes('-') ? a.replace(/-/g'/') : a)
                      ft = b
                  }
                  const map = {
                      YString(dt.getFullYear()), //4位數(shù) 年份
                      MString(dt.getMonth() + 1).padStart(20), // 2位數(shù) 月份
                      DString(dt.getDate()).padStart(20), // 2位數(shù) 日期
                      HString(dt.getHours()).padStart(20), // 2位數(shù) 時(shí)
                      mString(dt.getMinutes()).padStart(20), // 2位數(shù) 分
                      sString(dt.getSeconds()).padStart(20), //2位數(shù) 秒
                      SString(dt.getMilliseconds()).padStart(30), // 3位數(shù) 毫秒
                      QMath.floor((dt.getMonth() + 3) / 3) + '' //季度
                  }
                  return ft.replace(/\[([^\]]+)]|y{1,4}|Y{1,4}|M{1,2}|d{1,2}|D{1,2}|h{1,2}|H{1,2}|m{1,2}|s{1,2}|q|t|S{1,3}/g, match => {
                      // 匹配中的首字符
                      let k = match[0]
                      // 匹配到的字符串長(zhǎng)度
                      let len = match.length
                      switch (k) {
                          case 'y':
                          case 'Y':
                              return match.replace(new RegExp('((' + k + ')+)''g'), a => map.Y.substr(4 - a.length))
                          case 'M':
                              return len == 1 ? Number(map.M) : map.M
                          case 'D':
                          case 'd':
                              return len == 1 ? Number(map.D) : map.D
                          case 'H':
                          case 'h':
                              return len == 1 ? Number(map.H) : map.H
                          case 'm':
                              return len == 1 ? Number(map.m) : map.m
                          case 's':
                              return len == 1 ? Number(map.s) : map.s
                          case 'S':
                              return match.replace(new RegExp('((' + k + ')+)''g'), a => map.S.substr(3 - a.length))
                          case '[':
                              return match.replace(/\[|\]/g'')
                          case 'q':
                              return map.Q
                          default:
                              return match
                      }
                  })
              } catch (e) {
                  return new Date(''// Invalid Date
              }
          }
          復(fù)制代碼

          實(shí)現(xiàn)完了,到底具有那些能力,我們測(cè)試下,大致羅列如下:


          // 使用默認(rèn)格式格式化當(dāng)前日期
          format()

          // 指定格式來格式化當(dāng)前日期
          format('yyyy-MM-dd')

          // 使用默認(rèn)格式來格式化指定日期
          format('2021/1/1')
          // => "2021-01-01 00:00:00"

          // 指定格式來格式化指定日期
          format('2021/1/1''yy-MM-dd hh:mm:ss S')
          // => "21-01-01 00:00:00 000"

          // 模板處理特殊字符
          format('2021/1/1''yyyy-MM-dd [yyyy]')
          // => "2021-01-01 yyyy"

          format('2021/1/1''2021/1/1是屬于第q季度')
          // => "2021/1/1是屬于第1季度"

          format('當(dāng)前時(shí)間是屬于第q季度')
          復(fù)制代碼

          所有可用解析標(biāo)記的列表,如果又其他需求,可自行擴(kuò)展即可

          標(biāo)識(shí)        | 示例      | 描述            |
          | --------- | ------- | ---------------- |
          | YY/yy     | 18      | 年,兩位數(shù)        |
          | YYYY/yyyy | 2018    | 年,四位數(shù)        |
          | M         | 1-12    | 月,從 1 開始     |
          | MM        | 01-12   | 月,兩位數(shù)字      |
          | D/d       | 1-31    | 日               |
          | DD/dd     | 01-31   | 日,兩位數(shù)        |
          | H/h       | 0-23    | 24 小時(shí)           |
          | HH/hh     | 00-23   | 24 小時(shí),兩位數(shù)    |
          | h         | 1-12    | 12 小時(shí)           |
          | hh        | 01-12   | 12 小時(shí),兩位數(shù)    |
          | m         | 0-59    | 分鐘              |
          | mm        | 00-59   | 分鐘,兩位數(shù)       |
          | s         | 0-59    | 秒                |
          | ss        | 00-59   | 秒,兩位數(shù)         |
          | S         | 0-9     | 毫秒(百),一位數(shù) |
          | SS        | 00-99   | 毫秒(十),兩位數(shù) |
          | SSS       | 000-999 | 毫秒,三位數(shù)       |
          | q         | 季度    | 返回 1 ~ 4         |
          復(fù)制代碼

          該方法感覺優(yōu)化不了什么了,瞬間打臉,嘎嘎的響?。?!

          dalian.gif

          最后,我還是想厚顏無恥的要個(gè)贊,后面會(huì)繼續(xù)分享其他需求函數(shù),你的贊是我的支持,寫的不好請(qǐng)見諒,后面會(huì)繼續(xù)提高寫作水平!

          關(guān)于本文

          來源:rookie_fly

          https://juejin.cn/post/7001712210095374373


          最后

          歡迎關(guān)注【前端瓶子君】??ヽ(°▽°)ノ?
          回復(fù)「算法」,加入前端編程源碼算法群,每日一道面試題(工作日),第二天瓶子君都會(huì)很認(rèn)真的解答喲!
          回復(fù)「交流」,吹吹水、聊聊技術(shù)、吐吐槽!
          回復(fù)「閱讀」,每日刷刷高質(zhì)量好文!
          如果這篇文章對(duì)你有幫助,在看」是最大的支持
           》》面試官也在看的算法資料《《
          “在看和轉(zhuǎn)發(fā)”就是最大的支持



          瀏覽 33
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  免费看黄色视频 | 黄色视频在线观看www | 99最新视频在线 | 大香蕉亚洲在线 | 亚洲,日韩,aⅴ在线欧美 |