import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatterExample {
public static void main(String[] args) {
// 获取当前日期和时间
LocalDateTime now = LocalDateTime.now();
System.out.println("未格式化的时间: " + now);
// 创建自定义格式器
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 格式化时间
String formattedDate = now.format(formatter);
System.out.println("格式化后的时间: " + formattedDate);
// 解析字符串为LocalDateTime对象
LocalDateTime parsedDate = LocalDateTime.parse(formattedDate, formatter);
System.out.println("解析后的时间: " + parsedDate);
}
}
java.time.LocalDateTime和java.time.format.DateTimeFormatter。LocalDateTime.now()方法获取当前的日期和时间。DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")创建一个自定义的日期时间格式器,指定输出格式为年-月-日 时:分:秒。now.format(formatter)将当前日期时间格式化为指定的字符串格式。LocalDateTime.parse(formattedDate, formatter)将格式化后的字符串解析回LocalDateTime对象。这段代码展示了如何使用DateTimeFormatter进行日期时间的格式化和解析。
上一篇:java去除字符串首尾空格
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站