js 时间格式化 yyyy-MM-dd
时间: 2023-09-01 14:10:37 浏览: 48
您可以使用以下代码进行 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 hh:MM:ss
你可以使用 JavaScript 的 Date 对象来格式化日期时间。以下是一个示例函数,将 Date 对象转换为格式为 "yyyy-mm-dd hh:MM:ss" 的字符串:
```javascript
function formatDate(date) {
var year = date.getFullYear();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var hour = ('0' + date.getHours()).slice(-2);
var minute = ('0' + date.getMinutes()).slice(-2);
var second = ('0' + date.getSeconds()).slice(-2);
return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
}
// 示例使用
var date = new Date();
console.log(formatDate(date)); // 输出格式为 "yyyy-mm-dd hh:MM:ss" 的当前日期时间字符串
```
请注意,上述代码中的 `slice(-2)` 用于确保月份、日期、小时、分钟和秒数都是两位数字。如果某个值小于 10,则将其前面添加一个零。
js时间格式化yyyy-MM-dd HH:mm:ss
可以使用JavaScript中的Date对象和字符串的方法来格式化时间,代码如下:
```
function formatDate(date) {
let year = date.getFullYear();
let month = ('0' + (date.getMonth() + 1)).slice(-2);
let day = ('0' + date.getDate()).slice(-2);
let hours = ('0' + date.getHours()).slice(-2);
let minutes = ('0' + date.getMinutes()).slice(-2);
let seconds = ('0' + date.getSeconds()).slice(-2);
return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
}
// 使用示例
let now = new Date();
console.log(formatDate(now)); // 输出格式为:yyyy-MM-dd HH:mm:ss
```
这段代码可以将当前时间格式化为指定的字符串格式。如果需要将其他时间格式转换为该格式,只需要将`now`替换为相应的时间对象即可。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)