首页 > 解决方案 > Truncate date to start of the day in a given timeZone

问题描述

I am looking to truncate the date time to start of the day for the given timeZone. If the current time is Mon Aug 24 15:38:42 America/Los_Angeles, it should be truncated to start of the day Mon Aug 24 00:00:00 America/Los_Angeles which then later should be converted to equivalent UTC time.

I have explored the methods provided by Joda Time Library, Apache Commons Library and ZonedDateTime but all of them truncate the date time in UTC and not to specific timeZone.

Can someone help me with this? Thanks in advance.

标签: datejava-8timezonejodatime

解决方案


You can use ZonedDateTime. Use toLocalDate() on ZonedDateTime to get LocalDate then atStartOfDay on LocalDate with zone of ZonedDateTime instance to get the start of day.

Example:

ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
ZonedDateTime startOfDay = now.toLocalDate().atStartOfDay(now.getZone());

DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME;
System.out.println(now.format(formatter));         // Mon, 24 Aug 2020 10:41:41 -0700
System.out.println(startOfDay.format(formatter));  // Mon, 24 Aug 2020 00:00:00 -0700

推荐阅读