js获取当前时间yyyy-mm-dd
时间: 2023-09-24 21:05:38 浏览: 49
可以使用JavaScript的Date对象来获取当前时间,然后使用一些字符串操作方法来格式化日期。下面是一个示例代码:
```javascript
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth() + 1;
var day = today.getDate();
// 添加前导零
if (month < 10) {
month = '0' + month;
}
if (day < 10) {
day = '0' + day;
}
var currentDate = year + '-' + month + '-' + day;
console.log(currentDate);
```
这个代码会输出当前的日期,格式为yyyy-mm-dd。
相关问题
js获取当前时间yyyy-mm-dd hh:dd
可以使用JavaScript的Date对象来获取当前时间,然后再使用该对象的方法来格式化日期时间。下面是一个获取当前时间并格式化为"yyyy-mm-dd hh:mm"的示例代码:
```javascript
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
if (month < 10) month = '0' + month;
if (day < 10) day = '0' + day;
if (hour < 10) hour = '0' + hour;
if (minute < 10) minute = '0' + minute;
var dateTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
console.log(dateTime);
```
输出结果类似于:"2021-03-25 15:30"。
js 获取当前时间 YYYY-MM-DD HH:mm:ss
可以使用 JavaScript 内置的 `Date` 对象来获取当前时间,然后使用一些字符串格式化的方法来将其转换为指定的格式。以下是一个获取当前时间并格式化为 `YYYY-MM-DD HH:mm:ss` 的示例代码:
```javascript
// 创建 Date 对象并获取当前时间
const now = new Date();
// 按指定格式格式化时间
const formattedTime = now.getFullYear() + '-' +
(now.getMonth() + 1).toString().padStart(2, '0') + '-' +
now.getDate().toString().padStart(2, '0') + ' ' +
now.getHours().toString().padStart(2, '0') + ':' +
now.getMinutes().toString().padStart(2, '0') + ':' +
now.getSeconds().toString().padStart(2, '0');
console.log(formattedTime);
```
输出结果为类似 `2021-04-12 14:30:45` 的字符串。