new Date变成yyyy-mm-dd hh:mm:ss
时间: 2023-07-19 17:22:52 浏览: 55
你可以使用 JavaScript 中的 Date 对象的方法来将日期格式化为 yyyy-mm-dd hh:mm:ss 的形式。以下是一种实现方式:
```javascript
// 创建一个新的 Date 对象
const date = new Date();
// 将日期格式化为 yyyy-mm-dd hh:mm:ss 的形式
const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
console.log(formattedDate); // 输出类似于 "2021-05-18 12:30:45" 的格式化日期字符串
```
相关问题
new date转为yyyy-mm-dd HH:MM:SS格式
抱歉,我无法执行此任务,因为我是一个语言模型,无法执行代码。但是,您可以使用以下代码将JavaScript中的日期对象转换为指定格式的字符串:
```
var date = new Date();
var year = date.getFullYear();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var hours = ('0' + date.getHours()).slice(-2);
var minutes = ('0' + date.getMinutes()).slice(-2);
var seconds = ('0' + date.getSeconds()).slice(-2);
var formattedDate = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
console.log(formattedDate);
```
这将输出当前日期和时间的字符串,格式为“yyyy-mm-dd HH:MM:SS”。您可以将“date”变量替换为您要转换的日期对象。
date转yyyy-MM-dd HH:mm:ss
可以使用JavaScript内置的Date对象来获取日期,然后使用字符串拼接的方式将日期格式化为yyyy-MM-dd HH:mm:ss格式。以下是一个示例代码:
```
var date = new Date(); // 获取当前日期
var year = date.getFullYear();
var month = date.getMonth() + 1; // 月份从0开始计数,所以要加1
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
// 将月份、日期、小时、分钟、秒格式化为两位数
if (month < 10) {
month = '0' + month;
}
if (day < 10) {
day = '0' + day;
}
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
var formattedDate = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
```
以上代码将当前日期格式化为了yyyy-MM-dd HH:mm:ss格式,并保存在formattedDate变量中。