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

JavaScript如何不使用正则从ISO日期字符串提取周几、小时、日期字段

不存在名为toDateDayString的原生内置方法,但你可以完全基于Date对象的toLocale*系列内置方法实现需求,全程不需要写正则表达式,实现逻辑如下:
先将拿到的ISO格式日期字符串转换为Date实例,再通过内置的本地化格式化方法分别提取三个字段即可,修改后的代码片段如下:

const allMessages = [] 

await subClient.conversations.services(convoServiceSid)
           .conversations(convo)
           .messages
           .list({limit: 20})
           .then(messages => messages.forEach(m => {
              // 先将ISO字符串转为Date对象
              const date = new Date(m.dateCreated)
              allMessages.push({
                "messagesId": m.conversationSid, 
                "time": {
                  // 提取短格式星期名,对应示例中的Tue
                  day: date.toLocaleDateString('en-US', { weekday: 'short' }),
                  // 提取12小时制时分,对应示例中的11:54 AM
                  hour: date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true }),
                  // 提取月日年格式日期,对应示例中的May 5, 2019
                  date: date.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })
                }
              })
            }));

res.json(allMessages)

如果后续需要适配其他语言的显示格式,只需要把toLocale*方法的第一个参数en-US换成对应语言编码即可,无需修改其他逻辑。

内容的提问来源于stack exchange,提问作者AmandaConda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:54:06