格式化日期(天天看開源項目學一招半式)

開源項目連接地址javascript

代碼以下

function formatType(type, format, value, regExpAttributes) {
  const regExpMap = {
    year: '(Y+)',
    month: '(M+)',
    date: '(D+)',
    hour: '(h+)',
    minute: '(m+)',
    second: '(s+)',
    quarter: '(q+)',
    millisecond: '(S)'
  }

  if (new RegExp(regExpMap[type], regExpAttributes).test(format)) {
    const replaceStr = type === 'year'
                       ? value.toString().substr(4 - RegExp.$1.length)
                       : (RegExp.$1.length === 1) ? value : pad(value)
    format = format.replace(RegExp.$1, replaceStr)
  }

  return format
}

function pad(value) {
  return ('00' + value).substr(('' + value).length)
}

function formatDate(date, format) {
  const map = {
    year: {
      value: date.getFullYear(),
      regExpAttributes: 'i'
    },
    month: {
      value: date.getMonth() + 1
    },
    date: {
      value: date.getDate(),
      regExpAttributes: 'i'
    },
    hour: {
      value: date.getHours(),
      regExpAttributes: 'i'
    },
    minute: {
      value: date.getMinutes()
    },
    second: {
      value: date.getSeconds()
    },
    quarter: {
      value: Math.floor((date.getMonth() + 3) / 3),
      regExpAttributes: 'i'
    },
    millisecond: {
      value: date.getMilliseconds()
    }
  }

  for (const key in map) {
    format = formatType(key, format, map[key].value, map[key].regExpAttributes)
  }

  return format
}
複製代碼

測試

console.log(
  'result:',
  formatDate(new Date(), 'YYYY.MM.DD hh:mm')
)
複製代碼

演繹過程

根據傳入日期對象參數,得到對應的月份7, 根據匹配規則YYYY.MM.DD hh:mm, 經過正則(M+)找出MM, 接着把7替換MM, 同時使用pad函數處理下7 => 07, 24 => 24狀況,以此類推。java

補零pad

function pad(value) {
  return ('00' + value).substr(('' + value).length)
}
複製代碼

若是值1位數7, 前面加00, 即007, 剪掉0, 即07git

若是值2位數24, 前面加00, 即0024, 剪掉00, 即24github

共同點,剪掉的是值的長度。bash

數字 + 字符串,必定是字符串相加,不是數字的累加,這點要注意。函數

GITHUB倉庫,歡迎Star測試

相關文章
相關標籤/搜索