js new Date() 转换为 年-月-日 (单月/日自动补0)
时间: 2023-11-28 13:48:37 浏览: 38
可以使用 JavaScript 中的 Date 对象来获取当前的年、月、日等信息,并将其格式化为符合要求的日期字符串。
以下是一个将当前日期格式化为 "YYYY-MM-DD" 格式的例子:
```javascript
const today = new Date();
const year = today.getFullYear();
const month = ('0' + (today.getMonth() + 1)).slice(-2); // 月份需要加1,且不足两位数要补0
const day = ('0' + today.getDate()).slice(-2); // 不足两位数要补0
const formattedDate = `${year}-${month}-${day}`;
console.log(formattedDate); // 输出类似 "2022-10-01" 的日期字符串
```
如果需要将其他日期转换为符合要求的格式,只需要将 `new Date()` 中的参数替换为对应的日期即可。例如:
```javascript
const dateStr = '2022-10-01';
const date = new Date(dateStr);
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
const formattedDate = `${year}-${month}-${day}`;
console.log(formattedDate); // 输出 "2022-10-01"
```