Record
// 获取今年的开始时间
const now = new Date();
const yearStart = new Date(now.getFullYear(), 0, 1);
const yearStartFormatted = formatDate(yearStart);
// 获取当前时间
const currentFormatted = formatDate(now);
// 格式化日期时间为指定格式 "YYYY-MM-DD HH:mm:ss"
function formatDate(date) {
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
console.log(yearStartFormatted); // 输出今年的开始时间,例如:2022-01-01 00:00:00
console.log(currentFormatted); // 输出当前时间,例如:2022-12-05 13:36:00
New Date(now.getFullYear(), 0, 1) means:
-
0
Represents the month of January (January has index 0 in JavaScript). Because months are counted from 0, 0 represents January, 1 represents February, and so on. -
1
Represents a date, which is the first day of each month.
const month = (date.getMonth() + 1).toString().padStart(2, '0') means:
-
(date.getMonth() + 1)
: Since the month is counted from 0, we need to add 1 to the obtained month value to get the actual month. Here, parentheses are used to(date.getMonth() + 1)
wrap it to ensure that the correct month value is obtained before the addition operation. -
.toString()
:toString()
is a JavaScript method that converts a number to a string. Here we convert the month value calculated earlier to a string. -
.padStart(2, '0')
:padStart()
It is a string method used to add specified characters to the beginning of the current string until the string reaches the specified length. Here, we pad the month string to a string of length 2, and if there are less than two digits, add the character '0' at the beginning.