跳到主要内容

Date Format 扩展

为 Date 对象添加自定义的格式化方法。

实现示例

// 扩展 Date 原型
Date.prototype.format = function(fmt) {
const o = {
'M+': this.getMonth() + 1,
'd+': this.getDate(),
'h+': this.getHours() % 12 || 12,
'H+': this.getHours(),
'm+': this.getMinutes(),
's+': this.getSeconds(),
'S+': this.getMilliseconds()
};

if (/(y+)/.test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
(this.getFullYear() + '').substr(4 - RegExp.$1.length)
);
}

for (let k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
const val = o[k] + '';
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length === 1 ? val : ('00' + val).substr(val.length)
);
}
}

return fmt;
};

// 使用
const date = new Date();
date.format('yyyy-MM-dd HH:mm:ss'); // '2024-01-15 22:30:00'
date.format('yyyy/MM/dd hh:mm:ss A'); // '2024/01/15 10:30:00 下午'

使用 Intl.DateTimeFormat(推荐)

const date = new Date();

// 中文格式
date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});

// 自定义格式
const formatter = new Intl.DateTimeFormat('zh-CN', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
formatter.format(date); // '2024 年 1 月 15 日'