2025-03-26

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

如題,因為現在 JS 有 Intl.DateTimeFormat 了,使用 Intl.DateTimeFormat 來將日期以 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"

然後再用 String.property.replace 處理

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"))
	.replace(" GMT", "")
	.replace(' ', 'T')

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

如果堅持要有 mile-second:

let date = new Date("2010-02-03 16:05:06.789-02:00")
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(date)
	.replace(" GMT", "." + date.getMilliseconds().toString().padStart(3, "0"))
	.replace(' ', 'T')

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

參考資料

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

沒有留言:

張貼留言