2025-03-26

使用 Intl.DateTimeFormat() constructor 將日期格式化成 ISO 8601 格式

可以使用 sv-SE (瑞典語)來處理

見下:

new Intl.DateTimeFormat(
	"sv-SE",
	{
		year: "numeric",
		month: "2-digit",
		day: "2-digit",
		hour: "2-digit",
		minute: "2-digit",
		second: "2-digit",
		hour12: false,
		timeZoneName: "longOffset",
	}
)

例如

let d = new Intl.DateTimeFormat(
	"sv-SE",
	{
		year: "numeric",
		month: "2-digit",
		day: "2-digit",
		hour: "2-digit",
		minute: "2-digit",
		second: "2-digit",
		hour12: false,
		timeZoneName: "longOffset",
		timeZone: "Asia/Taipei"
	}
).format(new Date("2010-02-03 16:05:06-02:00"))

console.log(d) 
//Output: "2010-02-04 02:05:06 GMT+08:00"

參考資料

Steven de Salas. (2021, Sep 2). Re: Get ISO 8601 using Intl.DateTimeFormat. Stack Overflow. https://stackoverflow.com/a/69032104

沒有留言:

張貼留言