如何用JavaScript/Moment.js将指定时间转换为目标自定义格式?
解决方案
使用 Moment.js 实现预期格式
calendar() 方法的设计目标是生成相对时间字符串(如"Yesterday"、"Today"),这就是你得到非预期结果的原因。要生成指定格式的绝对时间,应该使用 format() 方法并传入自定义格式字符串:
// 确保 Moment.js 已正确加载 const formattedDate = moment('2022-09-13T08:06:12.328+0000').format('DD MMMM [at] h:mm A'); console.log(formattedDate); // 输出:13 September at 1:36 PM
格式参数说明:
DD:两位数的日期(如13)MMMM:月份全称(如September)[at]:字面量文本,方括号包裹避免被解析为格式占位符h:12小时制的小时数(如1)mm:两位数的分钟数(如36)A:大写的AM/PM标识(如PM)
如果需要固定时区(而非依赖本地时区),可以添加时区配置:
// 例如强制使用 UTC+5:30 时区(对应示例中的1:36 PM) const formattedDate = moment('2022-09-13T08:06:12.328+0000') .tz('Asia/Kolkata') .format('DD MMMM [at] h:mm A');
注:使用时区功能需额外引入
moment-timezone库。
更优实现:原生 JavaScript(无需第三方库)
Moment.js 已停止维护,推荐使用原生 Intl.DateTimeFormat API,它支持国际化且性能更好:
const date = new Date('2022-09-13T08:06:12.328+0000'); // 提取日期和时间的各个部分 const parts = new Intl.DateTimeFormat('en-US', { day: 'numeric', month: 'long', hour: 'numeric', minute: 'numeric', hour12: true }).formatToParts(date); // 拼接成目标格式 const day = parts.find(p => p.type === 'day').value; const month = parts.find(p => p.type === 'month').value; const time = parts .filter(p => ['hour', 'literal', 'minute', 'dayPeriod'].includes(p.type)) .map(p => p.value) .join('') .trim(); const formattedDate = `${day} ${month} at ${time}`; console.log(formattedDate); // 输出:13 September at 1:36 PM
这种方法无需额外安装依赖,现代浏览器和Node.js均支持,且能灵活适配不同语言环境。
内容的提问来源于stack exchange,提问作者Jack
相关产品推荐
相关产品推荐

