js如何获取当前时间
在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"。

js获取当前时间年月日yyyy-mm-dd
您可以使用以下JavaScript代码来获取当前时间的年月日(格式为yyyy-mm-dd):
```javascript
function getCurrentDate() {
const now = new Date();
const year = now.getFullYear();
const month = (now.getMonth() + 1).toString().padStart(2, "0");
const day = now.getDate().toString().padStart(2, "0");
return `${year}-${month}-${day}`;
}
console.log(getCurrentDate());
```
这段代码首先创建了一个表示当前时间的`Date`对象。然后,我们分别获取年、月和日,并使用`padStart`方法确保月份和日期始终是两位数。醉后,我们将年、月和日拼接成所需的格式(yyyy-mm-dd)并返回。
