js如何获取当前时间

|2024-03-01 11:42:05|浏览:52

在JavaScript中可以使用`Date`对象来获取当前时间。以下是如何获取当前时间的代码示例:

```javascript
var currentDate = new Date();
console.log(currentDate);
```

运行以上代码会在控制台上打印当前时间的详细信息,包括年份、月份、日期、小时、分钟、秒等。如需获取特定格式的时间,可以使用`Date`对象的方法来获取指定部分的时间,例如:

```javascript
var currentDate = new Date();
var year = currentDate.getFullYear();
var month = currentDate.getMonth() + 1; // 月份从0开始,需要加1
var day = currentDate.getDate();
var hour = currentDate.getHours();
var minute = currentDate.getMinutes();
var second = currentDate.getSeconds();

console.log(year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second);
```

以上代码会打印当前时间的格式化结果,例如"2022-03-15 12:34:56"。

李亚
03-01 11:42优质作者
关注

为你推荐