【Java SE】时区,LocalDate,LocalDateTime

https://blog.csdn.net/qq_44749491/article/details/130123065

 

中国一共分了5个时区

哈尔滨 Asia/Harbin 长白时区GMT+8:30
上海 Asia/Shanghai 标准时区 GMT+8
重庆 Asia/Chongqing 陇蜀时区GMT+7
乌鲁木齐 Asia/Urumqi 藏时区GMT+6
喀什 Asia/Kashgar 昆仑时区GMT+5:30

java获取中国标准时间

LocalDate localDate = LocalDate.now(TimeZone.getTimeZone("Asia/Shanghai").toZoneId());
String date = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(localDate);

当月

String yearMonth = DateTimeFormatter.ofPattern("yyyy-MM").format(localDate);
startTime = yearMonth + "-01 00:00:00";
// 当前天 endTime
= DateTimeFormatter.ofPattern("yyyy-MM-dd").format(localDate) + " 23:59:59";
// 最后一天
endTime = yearMonth + "-" + month.length(localDate.isLeapYear()) + " 23:59:59";

过去一年

startTime = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(localDate.minusYears(1).plusDays(1)) + " 00:00:00";
endTime = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(localDate) + " 23:59:59";

获取时区

ZoneId zoneId = TimeZone.getTimeZone("Asia/Shanghai").toZoneId();

获取时间

LocalDate localDate = LocalDate.now(zoneId);
LocalDateTime localDateTime = LocalDateTime.now(zoneId);

格式化

String value = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(localDate);
String value = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(localDateTime);

LocalDateTime转Date

ZoneId zoneId = TimeZone.getTimeZone("Asia/Shanghai").toZoneId();
LocalDateTime localDateTime = LocalDateTime.parse("2022-10-24 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);
Date date = Date.from(zonedDateTime.toInstant());

 

posted @ 2022-07-15 14:31  翠微  阅读(505)  评论(0编辑  收藏  举报