十八、日期格式化,获取上周/上月

94 阅读1分钟
   const dateFormat = (time, format) => {
           if (!time) {
               console.error('格式化时,时间不能为空')
               return ''
           }
           const _time = typeof time === 'number' ? new Date(time) : time 
           let res = format;
           const obj = {
               'y+': _time.getFullYear(),
               'M+': _time.getMonth() + 1,
               'd+': _time.getDate(),
               'h+': _time.getHours(),
               'm+': _time.getMinutes(),
               's+': _time.getSeconds()
           }
           for (let k in obj) {
               if (new RegExp(`(${k})`).test(format)) {
                   res = res.replace(RegExp.$1, obj[k])
               }
           }
           return res
       }

       // 获取当前时间
       console.log(dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'))
       
       // 获取上一个月份
       const getLastMonth = function() {
           const t = new Date()
           const currentMonth = t.getMonth()
           t.setMonth(currentMonth - 1, 1)
           return dateFormat(t, 'yyyy-MM')
       }
       console.log(getLastMonth())
       
       // 获取上一周的时间范围
       const getLastWeekRange = function(type="yyyy-MM-dd") {
            const currentTime = new Date()
            const currentDay = currentTime.getDay()
            const _milli = 24 * 60 * 60 * 1000
            const end = currentTime.getTime() - (currentDay || 7) * _milli
            const start = end - 6 * _milli
            return [dateFormat(new Date(start), type), dateFormat(new Date(end), type)]
       }
       console.log(getLastWeekRange())