js获取当前时间年月日时分秒 代码简洁明了
时间: 2023-11-22 17:46:43 浏览: 46
以下是获取当前时间年月日时分秒的JavaScript代码,代码简洁明了:
```javascript
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
let hour = date.getHours();
let minute = date.getMinutes();
let second = date.getSeconds();
let currentDateTime = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
```
以上代码中,我们使用了JavaScript内置的Date对象来获取当前时间,然后通过调用Date对象的方法来获取年、月、日、时、分、秒等信息,并将它们拼接成一个字符串,最终得到了当前时间的年月日时分秒。
相关问题
js获取当前时间年月日时分秒实例
以下是获取当前时间年月日时分秒的 JavaScript 代码示例:
```javascript
// 获取当前时间
var now = new Date();
// 获取年份
var year = now.getFullYear();
// 获取月份(注意月份从0开始,需要加1)
var month = now.getMonth() + 1;
// 获取日期
var date = now.getDate();
// 获取小时数
var hour = now.getHours();
// 获取分钟数
var minute = now.getMinutes();
// 获取秒数
var second = now.getSeconds();
// 格式化输出时间
console.log(year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second);
```
输出结果可能类似于:`2021-08-01 12:34:56`。
js获取当前时间年月日时分秒
您可以使用JavaScript的Date对象来获取当前时间的年、月、日、时、分、秒。以下是一个示例代码:
```javascript
// 创建一个Date对象
var currentDate = new Date();
// 获取年份
var year = currentDate.getFullYear();
// 获取月份,注意月份从0开始,需要加1
var month = currentDate.getMonth() + 1;
// 获取日期
var day = currentDate.getDate();
// 获取小时
var hours = currentDate.getHours();
// 获取分钟
var minutes = currentDate.getMinutes();
// 获取秒数
var seconds = currentDate.getSeconds();
// 打印结果
console.log("当前时间:" + year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds);
```
上述代码将打印出当前时间的年、月、日、时、分、秒。请注意,月份从0开始计算,因此需要加1来得到实际的月份。