js 时间格式为yyyy-mm-dd
时间: 2024-01-05 13:04:55 浏览: 23
在 JavaScript 中,日期格式化可以使用 Date 对象的方法来实现。可以使用以下代码将日期格式化为 "yyyy-mm-dd" 的形式:
```javascript
const date = new Date();
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const formattedDate = `${year}-${month}-${day}`;
console.log(formattedDate);
```
这段代码首先创建了一个 Date 对象,然后使用 getFullYear()、getMonth() 和 getDate() 方法获取年、月和日。月份需要加 1,因为 getMonth() 方法返回的是从 0 开始的月份数字。接着使用 padStart() 方法在月份和日期前面添加 0,确保它们的格式为两位数。最后将格式化后的日期拼接成字符串并输出。
相关问题
js 时间格式化 yyyy-MM-dd
您可以使用以下代码进行 JS 时间格式化:
```
function formatDate(date) {
const year = date.getFullYear()
const month = (date.getMonth() + 1).toString().padStart(2, '0')
const day = date.getDate().toString().padStart(2, '0')
return year + '-' + month + '-' + day
}
// 使用示例
const date = new Date('2022/01/18')
console.log(formatDate(date)) // 输出 2022-01-18
```
希望对您有帮助!如果您有其它问题,请随时问我。
JS格式化时间为yyyy-mm-dd格式
可以使用 JavaScript 中的 Date 对象来格式化时间。以下是将当前时间格式化为 yyyy-mm-dd 格式的示例代码:
```javascript
const now = new Date();
const year = now.getFullYear();
const month = ('0' + (now.getMonth() + 1)).slice(-2);
const day = ('0' + now.getDate()).slice(-2);
const formattedDate = year + '-' + month + '-' + day;
console.log(formattedDate); // 输出当前日期的 yyyy-mm-dd 格式
```
如果要格式化指定的时间,可以将时间字符串或时间戳作为参数传递给 `new Date()`。例如,要将时间戳 `1623896100000` 格式化为 yyyy-mm-dd 格式:
```javascript
const timestamp = 1623896100000;
const date = new Date(timestamp);
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); // 输出 2021-06-17
```