import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateFormatExample {
public static void main(String[] args) {
// 获取当前日期
LocalDate currentDate = LocalDate.now();
System.out.println("未格式化的日期: " + currentDate);
// 定义日期格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 格式化日期
String formattedDate = currentDate.format(formatter);
System.out.println("格式化后的日期: " + formattedDate);
// 解析字符串为日期
LocalDate parsedDate = LocalDate.parse(formattedDate, formatter);
System.out.println("解析后的日期: " + parsedDate);
}
}
java.time.LocalDate
和 java.time.format.DateTimeFormatter
,用于处理日期和日期格式化。LocalDate.now()
获取当前日期。DateTimeFormatter.ofPattern("yyyy-MM-dd")
定义一个日期格式模式,这里使用的是年-月-日的格式。currentDate.format(formatter)
将日期对象转换为指定格式的字符串。LocalDate.parse(formattedDate, formatter)
将格式化的字符串解析回日期对象。这个示例展示了如何在 Java 中进行日期的格式化和解析。
上一篇:java 数据类型
下一篇:java8 list
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站