如何在JavaScript中获取泰国时区的指定格式完整日期字符串?
提问
我需要获取泰国时区的日期,格式要求为:Thu Nov 10 2022 14:08:37 GMT+0800 (Malaysia Time)。我尝试过使用new Date().toLocaleString("en-US", {timeZone: "Asia/Bangkok"}),但未能得到想要的正确格式,问题可能出在.toLocaleString()上。请问有没有简单的实现方法?
解决方案
toLocaleString确实无法直接生成你要的带GMT偏移与时区名称的格式,这里提供两种简单实现方式:
方法一:借助Intl.DateTimeFormat精准拼接(推荐)
利用formatToParts拆分日期的各个组件,再手动组合成目标格式,兼容性更好且准确性高:
function getThailandFormattedDate() { const now = new Date(); // 获取日期时间核心部分的组件 const dateComponents = new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Bangkok', weekday: 'short', month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }).formatToParts(now); const dateTimeStr = `${dateComponents.find(p => p.type === 'weekday').value} ${dateComponents.find(p => p.type === 'month').value} ${dateComponents.find(p => p.type === 'day').value} ${dateComponents.find(p => p.type === 'year').value} ${dateComponents.find(p => p.type === 'hour').value}:${dateComponents.find(p => p.type === 'minute').value}:${dateComponents.find(p => p.type === 'second').value}`; // 格式化时区偏移(将GMT+07:00转为GMT+0700) const offsetComponents = new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Bangkok', timeZoneName: 'longOffset' }).formatToParts(now); const formattedOffset = offsetComponents.find(p => p.type === 'timeZoneName').value.replace(':', ''); // 获取时区名称(泰国时区为Indochina Time) const tzNameComponents = new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Bangkok', timeZoneName: 'long' }).formatToParts(now); const tzName = tzNameComponents.find(p => p.type === 'timeZoneName').value; return `${dateTimeStr} ${formattedOffset} (${tzName})`; } // 调用示例 console.log(getThailandFormattedDate());
输出示例:Thu Nov 10 2022 14:08:37 GMT+0700 (Indochina Time)
方法二:基于UTC时间直接计算(更简洁)
泰国时区为UTC+7且无夏令时,可直接计算泰国时间后拼接格式:
function getThailandFormattedDate() { const now = new Date(); // 计算泰国时间的时间戳(UTC时间加7小时) const thaiTimestamp = now.getTime() + (7 * 60 * 60 * 1000); const thaiDate = new Date(thaiTimestamp); // 提取日期时间部分,去掉本地时区信息 const dateTimePart = thaiDate.toString().split(' GMT')[0]; // 拼接泰国时区的偏移和名称 return `${dateTimePart} GMT+0700 (Indochina Time)`; }
内容的提问来源于stack exchange,提问作者SNAZ
相关产品推荐
相关产品推荐

