JavaScript 日期格式化:全面指南及示例
可以使用 JavaScript 中的 Date 对象和相关方法来格式化日期。
以下是一些常用的格式化方法:
- toDateString() - 返回格式为周几 月 日 年的日期字符串。
const date = new Date();
const formattedDate = date.toDateString();
console.log(formattedDate); // 'Fri Oct 08 2021'
- toISOString() - 返回格式为 ISO 日期字符串,例如 '2021-10-08T09:58:53.000Z'。
const date = new Date();
const formattedDate = date.toISOString();
console.log(formattedDate); // '2021-10-08T09:58:53.000Z'
- toLocaleDateString() - 返回格式为本地日期字符串,例如 '10/8/2021'。
const date = new Date();
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
const formattedDate = date.toLocaleDateString('en-US', options);
console.log(formattedDate); // 'Friday, October 8, 2021'
- toLocaleTimeString() - 返回格式为本地时间字符串,例如 '9:58:53 AM'。
const date = new Date();
const options = { hour12: true, hour: 'numeric', minute: 'numeric', second: 'numeric' };
const formattedTime = date.toLocaleTimeString('en-US', options);
console.log(formattedTime); // '9:58:53 AM'
- toLocaleString() - 返回格式为本地日期和时间字符串,例如 '10/8/2021, 9:58:53 AM'。
const date = new Date();
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour12: true, hour: 'numeric', minute: 'numeric', second: 'numeric' };
const formattedDateTime = date.toLocaleString('en-US', options);
console.log(formattedDateTime); // 'Friday, October 8, 2021, 9:58:53 AM'
注意:以上方法都返回字符串,而不是 Date 对象。如果需要进行日期计算或比较,建议仍然使用 Date 对象。
原文地址: https://www.cveoy.top/t/topic/obMD 著作权归作者所有。请勿转载和采集!