把Date格式化yyyy-MM-dd
时间: 2024-01-05 11:05:09 浏览: 26
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!
相关问题
js date格式化yyyy-mm-dd
你可以使用 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" 的日期格式。
java date格式化yyyy-mm-dd
Java中使用SimpleDateFormat类来格式化日期。下面是一个示例代码,将当前日期格式化为yyyy-MM-dd格式:
```
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String format = formatter.format(new Date());
System.out.println(format);
```