如何从时间戳字符串中提取月份和年份并格式化输出
问题原因
- 你定义的
x是字符串类型,不是Date时间对象,不支持时间格式化的toLocaleString方法,直接调用不会生效。 toLocaleString不会修改原变量,只会返回格式化后的新字符串,你之前没有接收这个返回值,打印的还是原始时间字符串。- 你需要的是完整月份名(如
September),参数month要传long而非short,short对应的是缩写格式(如Sep)。
修正后代码
// 先将时间字符串转为Date对象 const timeDate = new Date("2021-09-08T17:00:00.000Z"); // 调用格式化方法接收返回值,month传long获取完整月份名 const x = timeDate.toLocaleString('en-us', { month: 'long', year: 'numeric' }); console.log(x); // 输出 September 2021
如果需要强制读取UTC时区的年月,避免本地时区差异导致的日期偏移,可以在配置项中增加timeZone: 'UTC'参数:
const x = timeDate.toLocaleString('en-us', { month: 'long', year: 'numeric', timeZone: 'UTC' });
内容的提问来源于stack exchange,提问作者BreadBoard.ini
相关产品推荐
相关产品推荐

