在 JavaScript 中,可以使用
toISOString()
方法来将日期对象格式化为 ISO 8601 格式的字符串,该字符串的格式为
YYYY-MM-DDTHH:mm:ss.sssZ
,其中
T
是日期和时间之间的分隔符,
Z
表示时区是 UTC。
const date = new Date();
const isoString = date.toISOString();
console.log(isoString); // Output: "2022-12-20T12:34:56.789Z"
如果你想要的格式是 YYYYMMDDTHHMMSS
,可以使用以下代码来转换:
const date = new Date();
const formattedDate = date.toISOString().replace(/[-:]/g, '').slice(0, -5);
console.log(formattedDate); // Output: "20221220T123456"
注意,这种方法只能在浏览器环境中使用,因为它依赖于 Date.prototype.toISOString
方法。如果你需要在服务器端或其他环境中使用,可能需要使用其他方法来格式化日期。