js中new date yyyy-mm-dd HH:mm:ss
时间: 2024-05-18 10:18:21 浏览: 168
在JavaScript中,使用`new Date()`来创建一个新的日期对象。要将日期格式化为`yyyy-mm-dd HH:mm:ss`的格式,可以使用以下方法之一:
方法一:
```
let date = new Date();
let year = date.getFullYear();
let month = String(date.getMonth() + 1).padStart(2, '0');
let day = String(date.getDate()).padStart(2, '0');
let hours = String(date.getHours()).padStart(2, '0');
let minutes = String(date.getMinutes()).padStart(2, '0');
let seconds = String(date.getSeconds()).padStart(2, '0');
let formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
```
方法二:
```
let date = new Date();
let options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' };
let formattedDate = date.toLocaleString('en-US', options);
```
无论使用哪种方法,`formattedDate`将包含当前日期和时间的`yyyy-mm-dd HH:mm:ss`格式的字符串。
注意:上述代码中的`date`对象将获取当前日期和时间。如果你有特定的日期和时间,可以将其替换为你想要格式化的日期对象。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [Java 时间格式由yyyy-MM-dd HH:mm:ss 转换为 yyyy-MM-dd‘T‘HH:mm:ss](https://blog.csdn.net/weixin_44181419/article/details/128562911)[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: 33.333333333333336%"]
- *2* [js将日期格式转换为YYYY-MM-DD HH:MM:SS](https://download.csdn.net/download/weixin_38690545/14671498)[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: 33.333333333333336%"]
- *3* [【JS】JavaScript时间与时间戳相互转换 | 时间yyyy-MM-dd HH:mm:ss转为时间戳,时间戳转换为时间yyyy-MM-dd...](https://blog.csdn.net/weixin_42960907/article/details/121411661)[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: 33.333333333333336%"]
[ .reference_list ]
阅读全文