擺脫 moment

前言:

項目中遇到時間處理問題,又不想引入挺大的包(moment),只能本身封一下函數,下面列舉本人經常使用的函數函數

獲取某年某月的天數

有一種思路:判斷是不是閏年 -> 判斷月份 -> 得出天數code

const getDaysOfMonth = (year, month) => {
  const isLeapYear = !year % 4 && year % 100 || !year % 400

  if ([4, 6, 9, 11].includes(month)) {
    return 30
  }
     
  if ([1, 3, 5, 7, 8, 10, 12].includes(month)) {
    return 31
  }
  
  if (month === 2) {
    return isLeapYear ? 29 : 28
  }
}

第二種思路(推薦):Date 對象 API -> 獲得天數orm

const getetDaysOfMonth = (year, month) => new Date(year, month, 0).getDate()

格式化時間戳

格式化爲 2019-10-6 12:3:10 的形式:對象

const formatTime = (dateTime = Date.now()) => {
  const nums = new Date(dateTime).toLocaleString().match(/\d+/g)

  return nums.slice(0, 3).join('-') + ' ' + nums.slice(3).join(':')
}

格式化爲 2019-10-06 12:03:10 的形式,加個是否大於 10 的判斷便可:get

const formatTimeAddZero = (dateTime = Date.now()) => {
  const nums = new Date(dateTime).toLocaleString()
      .match(/\d+/g)
      .map(item => item < 10 ? `0${item}` : item)
  
  return nums.slice(0, 3).join('-') + ' ' + nums.slice(3).join(':')
}

// 若參數爲 2019:10:6 12:3:10 形式,直接用正則替換便可
const formatTimeAddZero = timeStr => timeStr.replace(/\b(\d)\b/g, '0$1')

格式化爲 2019年10月06日 12時03分10秒 的形式:it

// 在 map 時加上單位便可
const formatTimeToCN = (dateTime = Date.now()) => {
  const cn = ['年', '月', '日', '時', '分', '秒']
  const nums = new Date(dateTime).toLocaleString()
      .match(/\d+/g)
      .map((item, idx) => item < 10 ? `0${item}${cn[idx]}` : `${item}${cn[idx]}`)
 
  return nums.slice(0, 3).join('') + ' ' + nums.slice(3).join('')
}

獲取前一個星期

const getLastWeek = (year, month, day) => {
  const LEN = 7, lastWeek = []
  
  for (let i = 0; i < LEN; ++i) {
    lastWeek.push(
      new Date(new Date(year, month - 1, day).getTime() - i * 24 * 3600 * 1000).toLocaleDateString()
    )
  }
  
  return lastWeek
}

由上同理可得:ast

獲取某年某月某日的後三天:

const getNextThreeDays = (year, month, day) => {
  const LEN = 3, nextThreeDays = []
  for (let i = 0; i < LEN; ++i) {
    nextThreeDays.push(
      new Date(new Date(year, month - 1, day).getTime() + i * 24 * 3600 * 1000).toLocaleDateString()
    )
  }
  return nextThreeDays
}
相關文章
相關標籤/搜索