JS根据指定格式返回日期字符串

前言

这两天写需求要用到时间,就想找一个JavaScript按照指定格式返回时间字符串的方法。

结果不是代码太长,就是难理解,要么就是使用的方法已废弃。

所以抽时间写了一个dateFormat方法。

代码

const dateFormat = (
  fmt,
  date = new Date()
) => {
  const formatDate = new Date(date);
  const formatMap = {
    Y: (len) => formatDate.getFullYear().toString().slice(-len),
    M: (len) => (formatDate.getMonth() + 1).toString().padStart(len, '0'),
    D: (len) => formatDate.getDate().toString().padStart(len, '0'),
    H: (len) => formatDate.getHours().toString().padStart(len, '0'),
    m: (len) => formatDate.getMinutes().toString().padStart(len, '0'),
    s: (len) => formatDate.getSeconds().toString().padStart(len, '0'),
    S: (len) => formatDate.getMilliseconds().toString().padStart(len, '0'),
  };
  return fmt.replace(new RegExp(`[${Object.keys(formatMap).join('')}]+`, 'g'), match => formatMap[match[0]](match.length));
};

运行结果如下:

dateFormat('yyyy/MM/dd h:m:s::S')
// '2024/07/17 11:15:5::129'

dateFormat('年份:yyyy;月份:M;日期:d;时间:hh:mm:ss::S')
// '年份:2024;月份:7;日期:17;时间:11:15:05::702'

扩展

那么假设我现在又想加一个星期,怎么办呢?

可以在formatMap里增加一个d属性代表星期:

d: (len) => formatDate.getDay().toString()

那我想要dd返回周日ddd返回星期天呢?

d: (len) => len === 1 ? formatDate.getDay() : len === 2 ? `${['日', '一', '二', '三', '四', '五', '六'][formatDate.getDay()]}` : `星期${['天', '一', '二', '三', '四', '五', '六'][formatDate.getDay()]}`

增加个季度呢?

q: (len) => Math.ceil((formatDate.getMonth() + 1) / 3).toString().padStart(len, '0')

此时再运行:

dateFormat('yyyy/MM/dd h:m:s::S 季度q d dd ddd')
// '2024/07/17 11:17:38::562 季度3 2 周三 星期三'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值