如何将UTC时间转换为America/Chicago时区并按指定格式输出
解决JS中UTC转美国中部时区并格式化的问题
直接用Intl.DateTimeFormat(ES6+环境均支持)就能一步到位,不用绕弯子转Date对象再调用toISOString——后者本来就是输出UTC时区带Z标识的字符串,这就是你得到错误结果的核心原因。
方法一:快速格式化(正则辅助调整分隔符)
const formatOptions = { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false // 强制24小时制,需要12小时制可改为true }; // 先拿到带时区的结构化字符串 const rawChicagoTime = new Date().toLocaleString('en-US', formatOptions); // 替换分隔符成目标格式 const formattedTime = rawChicagoTime.replace(/(\d{2})\/(\d{2})\/(\d{4}), (\d{2}:\d{2}:\d{2})/, '$3-$1-$2-$4'); console.log(formattedTime); // 输出示例:"2022-07-15-12:01:57"
方法二:拆分拼接(无正则更直观)
如果你不想用正则,可以直接提取时间分量拼接:
const dtFormatter = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }); // 提取格式化后的各时间部分 const parts = dtFormatter.formatToParts(new Date()); const year = parts.find(p => p.type === 'year').value; const month = parts.find(p => p.type === 'month').value; const day = parts.find(p => p.type === 'day').value; const hour = parts.find(p => p.type === 'hour').value; const minute = parts.find(p => p.type === 'minute').value; const second = parts.find(p => p.type === 'second').value; // 拼接成目标格式 const formattedTime = `${year}-${month}-${day}-${hour}:${minute}:${second}`; console.log(formattedTime); // 输出示例:"2022-07-15-12:01:57"
你之前的代码问题出在哪?
你把toLocaleString返回的时区字符串重新转成Date对象,这个新对象本质还是基于UTC时间戳的,调用toISOString()必然输出UTC时区带Z标识的字符串,等于绕了一圈又回到UTC格式,完全没必要。
内容的提问来源于stack exchange,提问作者Louis M
相关产品推荐
相关产品推荐

