JS日期方法

此文主要整理一些日期相关的小方法
1.日期格式化
2.获取两个月之间的所有月
3.获取两天之间的所有天

1.日期格式化

function dateFormater(fmt, date) {
  if (!date) {
    return ''
  }
  if (typeof date !== 'object') {
    date = new Date(date)
  }
  let ret
  const opt = {
    'Y+': date.getFullYear().toString(),        // 年
    'm+': (date.getMonth() + 1).toString(),     // 月
    'd+': date.getDate().toString(),            // 日
    'H+': date.getHours().toString(),           // 时
    'M+': date.getMinutes().toString(),         // 分
    'S+': date.getSeconds().toString()          // 秒
    // 有其他格式化字符需求可以继续添加,必须转化成字符串
  }
  for (const k in opt) {
    ret = new RegExp('(' + k + ')').exec(fmt)
    if (ret) {
      fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
    }
  }
  return fmt
}
// 使用
let dateStr = dateFormater("YYYY-mm-dd HH:MM:SS", new Date())
console.log(dateStr) // 2021-03-01 10:37:43

2.获取两个月之间的所有月

function getNextMonth(date) {
  let year = new Date(date).getFullYear()
  let month = new Date(date).getMonth() + 1
  if (month === 12) {
    year += 1
    month = 1
  } else {
    month += 1
  }
  return `${year}-${(month + '').padStart(2, 0)}`
}
function getMonths(start, end) {
  const result = [
    this.dateFormater('YY-mm', start)
  ]
  let current = new Date(start).getTime()
  while (new Date(current) < new Date(end).getTime()) {
    current = getNextMonth(current)
    result.push(current)
  }
  return result
}
// 使用
let months = getMonths('2020-08', '2021-03')
console.log(month) // ["2020-08", "2020-09", "2020-10", "2020-11", "2020-12", "2021-01", "2021-02", "2021-03"]

3.获取两天之间的所有天

function getDates(start, end) {
  const result = [
    this.dateFormater('YY-mm-dd', start)
  ]
  const oneDay = 24 * 60 * 60 * 1000
  let current = new Date(start).getTime()
  while (current < new Date(end).getTime() - oneDay) {
    current += oneDay
    result.push(this.dateFormater('YY-mm-dd', current))
  }
  return result
}
// 使用
let dates = getDates('2021-2-25', '2021-03-01')
console.log(dates) // ["2021-02-25", "2021-02-26", "2021-02-27", "2021-02-28", "2021-03-01"]

4.获取最近多少天

function lastDays(day) {
  return new Date(new Date().getTime() - day * 24 * 3600 * 1000)
}
// 使用
let date = lastDays(30)
console.log(date) // Thu Oct 28 2021 19:11:10 GMT+0800 (中国标准时间)

5.获取未来多少天

function nextDays(day) {
  return new Date(new Date().getTime() + day * 24 * 3600 * 1000)
}
// 使用
let date = nextDays(30)
console.log(date) // Mon Dec 27 2021 19:12:39 GMT+0800 (中国标准时间)

持续更新中~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容