import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatExample {
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 parsedDate = LocalDateTime.parse(formattedDate, formatter);
System.out.println("解析后的日期时间对象: " + parsedDate);
}
}
LocalDateTime.now()
方法获取当前的日期和时间。DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
定义一个自定义的时间格式。format()
方法将 LocalDateTime
对象转换为指定格式的字符串。parse()
方法将格式化的字符串解析回 LocalDateTime
对象。这个示例展示了如何在 Java 中进行时间格式的转换,包括格式化和解析。
上一篇:java 包含字符串
下一篇:java 异步方法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站