js date格式化yyyy-mm-dd
时间: 2023-09-04 19:14:07 浏览: 45
你可以使用 JavaScript 中的 `Date` 对象来格式化日期。下面是一个将日期格式化为 "yyyy-mm-dd" 格式的示例代码:
```javascript
function formatDate(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
const currentDate = new Date();
const formattedDate = formatDate(currentDate);
console.log(formattedDate); // 输出当前日期的格式化结果,例如:2022-01-01
```
在上面的代码中,`formatDate` 函数接受一个 `Date` 对象作为参数,并通过使用 `getFullYear`、`getMonth` 和 `getDate` 方法获取年、月和日。然后,使用 `padStart` 方法来确保月份和日期始终为两位数。最后,将这些部分拼接在一起,形成 "yyyy-mm-dd" 的日期格式。
相关问题
js date格式化yyyy-mm-dd hh:mm:ss
要将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 ]
把Date格式化yyyy-MM-dd
Sure, you can format the Date to "yyyy-MM-dd" using the SimpleDateFormat class in Java. Here's an example code snippet:
```
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatter {
public static void main(String[] args) {
Date currentDate = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(currentDate);
System.out.println("Formatted Date: " + formattedDate);
}
}
```
This will give you the current Date formatted as "yyyy-MM-dd". Hope this helps!