我需要以這種格式獲取泰國時區:Thu Nov 10 2022 14:08:37 GMT 0800 (Malaysia Time). 我試過new Date().toLocaleString("en-US", {timeZone: "Asia/Bangkok"})但沒有得到我想要的正確格式,可能是因為.toLocaleString(). 有沒有簡單的方法來做到這一點?
uj5u.com熱心網友回復:
正如 deceze 建議的那樣,您可以使用Intl.DateTimeFormat和合適的選項來獲取您想要的值。然后您可以使用formatToParts根據需要重新組織它們,例如復制任何時區的 Date.prototype.toString 格式,您可以使用:
// Return timestamp in same format as Date.prototype.toString
// in designated timezone (IANA representative location)
function toTimezone(tz, date = new Date()) {
// Get parts except timezone name
let opts = {
year: 'numeric',
month: 'short',
day: '2-digit',
weekday: 'short',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZone: tz,
timeZoneName: 'shortOffset',
hour12: false
}
// To get full timezone name
let opts2 = {
hour: 'numeric',
timeZone: tz,
timeZoneName: 'long'
}
let toParts = opts => new Intl.DateTimeFormat('en', opts)
.formatToParts(date)
.reduce((acc, part) => {
acc[part.type] = part.value;
return acc;
}, Object.create(null));
let {year, month, day, weekday, hour, minute,
second, timeZoneName} = toParts(opts);
// Fix offset
let sign = /\ /.test(timeZoneName)? ' ' : '-';
let [oH, oM] = timeZoneName.substr(4).split(':');
let offset = `GMT${sign}${oH.padStart(2, '0')}${oM || '00'}`;
// Get timezone name
timeZoneName = toParts(opts2).timeZoneName;
return `${weekday} ${month} ${day} ${year} ${hour}:${minute}:${second} ${offset} (${timeZoneName})`;
}
// Examples
['Australia/Adelaide',
'Asia/Bangkok',
'Asia/Kolkata',
'America/New_York',
'Pacific/Yap',
'Pacific/Pago_Pago'
].forEach(tz => console.log(toTimezone(tz)));
對諸如shortOffset 之類的某些選項的支持可能尚未普及。支持時區的格式化庫是一個更簡單(也更可靠)的選項。:-)
uj5u.com熱心網友回復:
您可以使用一大堆選項配置語言環境字串格式化程式:
console.log(new Date().toLocaleString('en-US', {
timeZone: 'Asia/Bangkok',
weekday: 'short',
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZoneName: 'short',
hour12: false
}));
但是,它將輸出的確切格式始終取決于所使用的語言環境以及瀏覽器對如何為該語言環境設定日期格式的理解。如果您想更好地控制確切的格式,您需要自己拼湊起來:
const date = new Date();
const time = date.toLocaleString('en-US', {
timeZone: 'Asia/Bangkok',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZoneName: 'short',
hour12: false
});
const weekday = date.toLocaleString('en-US', {
timeZone: 'Asia/Bangkok',
weekday: 'short'
});
console.log(`${weekday} ${date.getFullYear()} ... ${time}`);
如果這看起來太復雜,請使用一些Luxon 之類的 3rd 方庫,它可以簡化一點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/532277.html
上一篇:時間序列-用弱提前資料替換缺失值
