Java带时区日期示例
import lombok.extern.slf4j.Slf4j;
import java.time.*;
@Slf4j(topic = "c.TimeInstance")
public class TimeInstance {
public static void main(String[] args) {
//带时区的当前时间 2022-09-14T16:09:54.875+08:00[Asia/Shanghai]
log.info("{}", ZonedDateTime.now());
//解析带时区的时间
ZonedDateTime parsedDateTime = ZonedDateTime.parse("2022-09-14T16:09:54.875+08:00[Asia/Shanghai]");
log.info("{}", parsedDateTime);
//获得时区
ZoneId zoneId = ZoneId.of("Europe/Paris");
log.info("一个时区ID:{},当前时区ID:{}", zoneId, ZoneId.systemDefault());
//系统时钟在默认时区下的当前日期时间
log.info("{}", LocalDateTime.now());
LocalDateTime curDateTime = LocalDateTime.now();
log.info("当前年:{}, 月:{}, 日:{}", curDateTime.getYear(), curDateTime.getMonthValue(), curDateTime.getDayOfMonth());
//指定日期时间
LocalDateTime localDateTime = curDateTime.withYear(2022).withMonth(10).withDayOfMonth(10);
log.info("{}", localDateTime);
//指定日期,年月日
log.info("{}", LocalDate.of(2022, Month.SEPTEMBER, 14));
//指定时间,时分秒纳秒
log.info("{}", LocalTime.of(22, 15));
}
}
程序输出:
2022-09-14 16:48:20 [main] c.TimeInstance - 2022-09-14T16:48:20.709+08:00[Asia/Shanghai]
2022-09-14 16:48:20 [main] c.TimeInstance - 2022-09-14T16:09:54.875+08:00[Asia/Shanghai]
2022-09-14 16:48:20 [main] c.TimeInstance - 一个时区ID:Europe/Paris,当前时区ID:Asia/Shanghai
2022-09-14 16:48:20 [main] c.TimeInstance - 2022-09-14T16:48:20.777
2022-09-14 16:48:20 [main] c.TimeInstance - 当前年:2022, 月:9, 日:14
2022-09-14 16:48:20 [main] c.TimeInstance - 2022-10-10T16:48:20.777
2022-09-14 16:48:20 [main] c.TimeInstance - 2022-09-14
2022-09-14 16:48:20 [main] c.TimeInstance - 22:15