js date格式化yyyy-mm-dd hh:mm:ss
时间: 2024-05-18 13:11:13 浏览: 249
要将JavaScript中的日期格式化为yyyy-MM-dd hh:mm:ss,可以使用以下代码:
```javascript
var date = new Date();
var formattedDate = date.getFullYear() + '-' +
('0' + (date.getMonth() + 1)).slice(-2) + '-' +
('0' + date.getDate()).slice(-2) + ' ' +
('0' + date.getHours()).slice(-2) + ':' +
('0' + date.getMinutes()).slice(-2) + ':' +
('0' + date.getSeconds()).slice(-2);
console.log(formattedDate);
```
这段代码首先获取当前的日期对象 `date`,然后根据需要的格式使用 `getFullYear()`、`getMonth()`、`getDate()`、`getHours()`、`getMinutes()`和 `getSeconds()` 方法获取日期的年、月、日、时、分和秒,并使用字符串拼接的方式将它们连接起来,最后输出结果。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [【JS】日期Date如何格式化为年月日yyyy-MM-dd hh:mm:ss](https://blog.csdn.net/weixin_43361722/article/details/122560822)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *3* [javascript date格式化示例](https://download.csdn.net/download/weixin_38526225/14905798)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文