在 JavaScript 中如何将日期格式化为 YYYY-MM-DD hh:mm:ss
在 JavaScript 中要将日期格式化为 yyyy-mm-dd hh:mm:ss
。需要遵循以下步骤:
- 使用 Date 对象上的方法获取日期的所有组成部分。
- 如果值小于 10,则在日、月、小时、分钟和秒中添加前导零。
- 用连字符连接与日期相关的字符串,用冒号连接与时间相关的字符串。
function padTo2Digits(num) {
return num.toString().padStart(2, '0');
}
function formatDate(date) {
return (
[
date.getFullYear(),
padTo2Digits(date.getMonth() + 1),
padTo2Digits(date.getDate()),
].join('-') +
' ' +
[
padTo2Digits(date.getHours()),
padTo2Digits(date.getMinutes()),
padTo2Digits(date.getSeconds()),
].join(':')
);
}
// 👇️ 2021-10-24 16:21:23 (yyyy-mm-dd hh:mm:ss)
console.log(formatDate(new Date()));
// 👇️️ 2025-05-04 05:24:07 (yyyy-mm-dd hh:mm:ss)
console.log(formatDate(new Date('May 04, 2025 05:24:07')));
我们做的第一件事是创建一个 padTo2Digits
函数,如果月、日、小时、分钟或秒只包含一个数字(小于 10),它将负责在其前面添加零。
function padTo2Digits(num) {
return num.toString().padStart(2, '0');
}
console.log(padTo2Digits(2)); // 👉️ '02'
console.log(padTo2Digits(6)); // 👉️ '06'
console.log(padTo2Digits(10)); // 👉️ '10'
我们要确保结果始终一致,并且有 2 位数字表示月、日、小时、分钟和秒,因此我们使用了 padStart
方法。
我们传递给 padTo2Digits 函数的第一个参数是字符串的总长度,因此如果它已经有 2 位数字,它将永远不会填充一个值。
接下来,我们创建了一个函数,它接受一个日期并将其格式化为 yyyy-mm-dd hh:mm:ss。
该函数使用以下 6 种与日期相关的方法。
- Date.getFullYear 方法 - 返回一个四位数字,表示对应于日期的年份。
- Date.getMonth - 返回一个介于 0(一月)和 11(十二月)之间的整数,表示给定日期的月份。 是的,不幸的是 getMonth 方法不是从 1 开始的。
- Date.getDate - 返回一个介于 1 到 31 之间的整数,表示特定日期的月份日期。
- Date.getHours - 返回指定日期的小时数。
- Date.getMinutes - 返回日期的分钟数。
- Date.getSeconds - 返回特定日期的秒数。
getMonth 方法返回从 0 到 11 的从零开始的月份索引,这意味着一月是 0,十二月是 11。
因为 getMonth 方法是从零开始的,所以我们在它的返回值上加了 1。
我们将年、月和日放在一个数组中,因此我们可以用连字符分隔符将它们连接起来。
console.log(['2024', '06', '22'].join('-'));
console.log(['2026', '09', '16'].join('-'));
这让我们得到格式为 yyyy-mm-dd 的日期。
下一步是将时间相关方法的返回值放在一个数组中,并用冒号连接它们。
console.log(['05', '24', '36'].join(':'));
console.log(['08', '13', '56'].join(':'));
我们使用加法 (+) 运算符在字符串中间添加一个空格,以获取格式为 yyyy-mm-dd hh:mm:ss 的日期。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。