function怎么获取年月日时分秒构成YYYY-MM-DD HH:mm:ss
时间: 2024-12-09 16:16:20 浏览: 61
在JavaScript中,你可以使用`Date`对象及其相关方法来获取当前日期和时间并格式化为"YYYY-MM-DD HH:mm:ss"的字符串形式。下面是一个示例函数,它会返回指定格式的日期时间:
```javascript
function getFormattedDateTime() {
const date = new Date(); // 获取当前日期和时间
const year = date.getFullYear(); // 年份四位数
let month = date.getMonth() + 1; // 月份,注意需要加1因为getMonth()返回0-11
const day = date.getDate(); // 月份内日子
// 格式化月份为两位数
if (month < 10) {
month = '0' + month;
}
const hours = date.getHours(); // 小时
const minutes = date.getMinutes(); // 分钟
const seconds = date.getSeconds(); // 秒数
// 如果小时、分钟或秒小于10,前面补零
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
```
现在,如果你想获取特定的日期时间,可以传入一个`Date`实例作为参数,或者直接调用这个函数获取当前时间。例如:
```javascript
const specificDate = new Date('2023-04-15T13:45:30'); // 或者不传参数,获取当前时间
console.log(getFormattedDateTime(specificDate)); // 输出格式化的日期时间
阅读全文
相关推荐



















