java yyyy-mm-dd 日期格式_Java中的日期时间格式化
时间: 2023-07-19 19:23:22 浏览: 116
在Java中,可以使用SimpleDateFormat类来进行日期时间格式化。以下是将日期格式化为yyyy-MM-dd格式的示例代码:
```
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = dateFormat.format(currentDate);
System.out.println("Formatted Date: " + formattedDate);
}
}
```
输出结果为:
```
Formatted Date: 2021-08-27
```
其中,dateFormat.format(currentDate)方法将当前日期格式化为指定的"yyyy-MM-dd"格式。可以根据需要修改日期时间格式化的格式。
相关问题
Java日期格式转yyyy-MM-dd 为 日期时间格式yyyy-MM-dd HH:mm:ss
在Java中,如果你有一个日期对象并想将其转换为"yyyy-MM-dd HH:mm:ss"这样的日期时间格式,你可以使用`SimpleDateFormat`类来进行格式化。首先,你需要创建一个`SimpleDateFormat`对象,指定目标格式,然后使用`format()`方法将日期转换为字符串。
以下是一个示例:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// 创建一个Date对象(这里假设你已经有了一个date变量)
Date date = ...;
// 定义日期格式和时间格式的对象
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 使用formatter获取年月日部分
String yearMonthDay = formatter.format(date);
// 将yearMonthDay合并到完整的日期时间格式中
String formattedDateTime = dateTimeFormatter.format(new Date(yearMonthDay + " 00:00:00"));
System.out.println(formattedDateTime);
}
}
```
在这个例子中,我们先将原始日期格式化为"yyyy-MM-dd",然后创建一个新的时间部分"00:00:00",最后将两者结合在一起。
日期格式化java yyyy-MM-dd
你可以使用Java中的SimpleDateFormat类来格式化日期。以下是一个示例代码,将日期格式化为"yyyy-MM-dd"格式:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
// 创建一个SimpleDateFormat对象,指定日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 获取当前日期
Date date = new Date();
// 使用SimpleDateFormat对象将日期格式化为指定格式的字符串
String formattedDate = sdf.format(date);
// 输出格式化后的日期字符串
System.out.println("Formatted date: " + formattedDate);
}
}
```
运行上述代码,将打印出当前日期的"yyyy-MM-dd"格式化结果。你可以根据需要修改日期对象和格式化字符串来适应不同的日期格式。
阅读全文
相关推荐












