如何将ISO时间字符串格式化为「DD/MM/YYYY 星期 HH:MM」样式?
问题:将ISO时间字符串格式化为指定样式
现有ISO时间字符串 2023-06-16T12:00:00Z,需要格式化为 「10/03/2013 Friday 12:00」 这样的样式(日/月/年 完整星期名 24小时制时间)。原代码仅能处理日期部分,代码如下:
const options = { year: 'numeric', month: 'numeric', day: 'numeric' }; const dt = new Date('2023-06-16T12:00:00Z').toLocaleDateString('tr-TR', options) console.log(dt)
修改方案
方案1:手动拼接各时间部分(格式更可控)
通过分别提取日期、星期、时间的各个部分,再按目标格式拼接,避免不同locale带来的格式差异:
const isoDate = '2023-06-16T12:00:00Z'; const date = new Date(isoDate); // 提取UTC时间的日、月、年(补零到2位) const day = String(date.getUTCDate()).padStart(2, '0'); const month = String(date.getUTCMonth() + 1).padStart(2, '0'); // 月份从0开始计数,需+1 const year = date.getUTCFullYear(); // 提取完整英文星期名 const weekday = date.toLocaleDateString('en-US', { weekday: 'long', timeZone: 'UTC' }); // 提取24小时制的时分 const time = date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false, timeZone: 'UTC' }); // 拼接成目标格式 const formattedDate = `${day}/${month}/${year} ${weekday} ${time}`; console.log(formattedDate); // 输出:16/06/2023 Friday 12:00
方案2:使用toLocaleString统一配置(依赖locale)
如果目标locale的默认格式接近需求,可以直接扩展options参数,使用toLocaleString同时获取日期、星期和时间:
const isoDate = '2023-06-16T12:00:00Z'; const options = { year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'long', hour: '2-digit', minute: '2-digit', hour12: false, timeZone: 'UTC' }; // 选择'en-GB' locale,其默认日期格式为日/月/年 let formattedDate = new Date(isoDate).toLocaleString('en-GB', options); // 移除默认生成的逗号,匹配目标格式 formattedDate = formattedDate.replace(/,/g, ''); console.log(formattedDate); // 输出:16/06/2023 Friday 12:00
关键说明
- 原代码使用
toLocaleDateString仅能获取日期部分,需改用toLocaleString或拆分获取时间、星期部分。 - 由于ISO时间是UTC时区,处理时需指定
timeZone: 'UTC',避免本地时区偏移影响结果。 - 使用
padStart(2, '0')确保日、月、时分均为两位数字格式。
内容的提问来源于stack exchange,提问作者Alperen Kapusuz
相关产品推荐
相关产品推荐

