欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

在JavaScript中添加星期和季度到时间格式化:dateFormat的使用方法

最编程 2024-08-03 21:14:02
...

网上有很多js格式化的帖子,但发现很少有带有星期的,感觉很不方便,现在将带有星期的时间格式化代码分享给大家,希望可以有所帮助

function dateFormat(f, d) {
    let fmt = f || 'yyyy-MM-dd hh:mm:ss'
    let date = d ? new Date(d) : new Date()
    let ret
    let weekArr = ['日', '一', '二', '三', '四', '五', '六']
    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(), // 秒
      'W+': date.getDay(), // 星期 
      'Q+': Math.ceil((date.getMonth() + 1) / 3) // 季度   // 有其他格式化字符需求可以继续添加,必须转化成字符串
    }
    for (let k in opt) {
      ret = new RegExp('(' + k + ')').exec(fmt)
      if (ret) {
        fmt = fmt.replace(
          ret[1],
          ret[1].length == 1
            ? k === 'W+' || k === 'Q+'
              ? weekArr[opt[k]]
              : opt[k]
            : opt[k].padStart(ret[1].length, '0')
        )
      }
    }
    return fmt
  }

使用时:

dateFormat() // 2022-07-04 08:30:17   默认返回时间格式根据需要自行修改

dateFormat('yyyy-MM-dd',1640995200000)  // 2022-01-01

dateFormat('yyyy-MM-dd hh:mm:ss 星期W 第Q季度', '2022-01-01')

// 2022-01-01 08:00:00 星期六 第一季度

偶尔,时间还需要范围,最常见的肯定是本月1日到当前日期,当然也有1日到月末,这需要怎么处理呢?且看我以下示例

// 本月1号

dateFormat('yyyy-MM-01')

// 本月月末

dateFormat('yyyy-MM-')  + getDaysInMonth()

获取指定月份的月末则需要dateFormat()和getDaysInMonth()都传入指定的时间

new Date(year, month, 0) 可以获取指定月份的天数

获取指定月份天数 --  默认本月

function getDaysInMonth(date) {
  date = date ? new Date(date) : new Date()
  const y = date.getFullYear()
  const m = date.getMonth() + 1
  return new Date(y,m,0).getDate()
}

当然,如果以上内容还不能满足你的需求, 那么你大概需要这个吧!点开看看吧,有没有你需要的

Moment.js 中文网