You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从时间戳字符串中提取月份和年份并格式化输出

问题原因

  • 你定义的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 03:51:04