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(带时区的时间)
ZoneId zoneId = ZoneId.of("Asia/Shanghai");
ZonedDateTime zonedDateTime = now.atZone(zoneId);
System.out.println("带时区的时间: " + zonedDateTime);
// 将 ZonedDateTime 转换为指定格式的字符串
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDate = zonedDateTime.format(formatter);
System.out.println("格式化后的时间: " + formattedDate);
// 将字符串转换回 ZonedDateTime
ZonedDateTime parsedDate = ZonedDateTime.parse(formattedDate + "[Asia/Shanghai]",
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[xxx]"));
System.out.println("解析后的时间: " + parsedDate);
}
}
LocalDateTime.now()
获取当前的本地时间。atZone(ZoneId)
方法将 LocalDateTime
转换为 ZonedDateTime
,并指定时区(例如:Asia/Shanghai
)。DateTimeFormatter
将 ZonedDateTime
转换为指定格式的字符串(如 yyyy-MM-dd HH:mm:ss
)。ZonedDateTime.parse()
方法将格式化的字符串解析回 ZonedDateTime
,注意需要带上时区信息。上一篇:java urldecode
下一篇:java快速入门
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站