JavaScript的Date对象通过getFullYear、getMonth等方法手动拼接可实现YYYY-MM-DD HH:mm:ss格式;简化版仅保留日期部分;toISOString适用于UTC时间处理;Intl.DateTimeFormat支持国际化输出,推荐用于本地化场景。

JavaScript 的 Date 对象本身不提供像其他语言那样的内置格式化字符串方法,但可以通过其提供的方法来获取年、月、日、时、分、秒等信息,并拼接成所需的日期格式。下面介绍几种常用方式来格式化日期。
使用 Date 对象的方法,如 getFullYear()、getMonth()(注意:月份从 0 开始)、getDate() 等,手动拼接成需要的格式。
例如,格式化为 YYYY-MM-DD HH:mm:ss:
function formatDate(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需+1
const day = String(date.getDate()).padStart(2, '0');
const hour = String(date.getHours()).padStart(2, '0');
const minute = String(date.getMinutes()).padStart(2, '0');
const second = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}
// 使用示例
const now = new Date();
console.log(formatDate(now)); // 输出:2025-04-05 14:30:25
如果只需要日期部分,可以简化函数:
function toDateString(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
console.log(toDateString(new Date())); // 输出:2025-04-05
如果处理的是标准时间或需要 ISO 格式,可以直接使用 toISOString(),然后截取所需部分:
const date = new Date();
const isoDate = date.toISOString(); // 返回:2025-04-05T06:30:25.123Z
const simpleDate = isoDate.split('T')[0]; // 只取日期部分:2025-04-05
这种方式适合用于保存或传输数据,但注意是 UTC 时间。
更现代的方式是使用 Intl.DateTimeFormat,支持本地化和灵活格式:
const date = new Date();
const formatter = new Intl.DateTimeFormat('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
});
console.log(formatter.format(date)); // 输出:2025/04/05 14:30:25(可根据 locale 调整)
可将分隔符替换为短横线:
formatter.format(date).replace(/\//g, '-'); // 2025-04-05 14:30:25
以上就是js date对象格式化日期的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号