js获取当前时间年月日字符串
时间: 2023-05-04 09:02:52 浏览: 452
获取当前时间的年月日字符串可以使用JavaScript的Date对象。首先,我们需要创建一个Date对象,这可以使用以下代码实现:
```
let currentDate = new Date();
```
此时,currentDate对象就包含了当前时刻的年、月、日、时、分、秒等信息。我们可以从中提取需要的信息,例如:
```
let year = currentDate.getFullYear();
let month = currentDate.getMonth() + 1; // 月份从0开始,所以要加1
let day = currentDate.getDate();
```
这样,我们就分别获取到了当前的年、月、日。其中,getFullYear()方法返回的是整数形式的四位数年份,getMonth()方法返回的是0到11的整数,getDate()方法返回的是1到31的整数。如果需要将这些数字转换成字符串形式,可以使用以下代码:
```
let yearString = year.toString(); // 将整数转换成字符串
let monthString = month < 10 ? '0' + month.toString() : month.toString(); // 如果月份在1到9之间,则在前面添加一个0,使字符串一致
let dayString = day < 10 ? '0' + day.toString() : day.toString(); // 如果日期在1到9之间,则在前面添加一个0,使字符串一致
let dateString = yearString + '-' + monthString + '-' + dayString; // 拼接成年-月-日格式的字符串
```
最后,我们将年、月、日组合成一个字符串,即可得到当前时间的年月日字符串。