import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class TimeConversionExample {
public static void main(String[] args) {
// 获取当前时间
LocalDateTime now = LocalDateTime.now();
System.out.println("当前时间: " + now);
// 将LocalDateTime转换为ZonedDateTime,指定时区
ZonedDateTime zonedDateTime = now.atZone(ZoneId.systemDefault());
System.out.println("带时区的时间: " + zonedDateTime);
// 将ZonedDateTime转换为其他时区的时间
ZonedDateTime zonedDateTimeInUtc = zonedDateTime.withZoneSameInstant(ZoneId.of("UTC"));
System.out.println("转换为UTC时间: " + zonedDateTimeInUtc);
// 格式化时间输出
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDate = now.format(formatter);
System.out.println("格式化后的时间: " + formattedDate);
}
}
LocalDateTime.now()获取当前的本地时间。atZone(ZoneId.systemDefault())将LocalDateTime转换为带有系统默认时区的ZonedDateTime。withZoneSameInstant(ZoneId.of("UTC"))将时间转换为指定时区(例如UTC)的时间。DateTimeFormatter来定义输出的时间格式,并通过format()方法将时间格式化为字符串。这段代码展示了如何在Java中进行时间的获取、时区转换和格式化操作。
上一篇:java 字符串转时间戳
下一篇:java 循环数组
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站