Reputation: 1091
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.
Upvotes: 1
Views: 1971
Reputation: 86379
ZonedDateTime
truncates in its own time zone. So it can be done a bit simpler than in the currently accepted answer (which is also a good and correct answer).
ZonedDateTime given = ZonedDateTime.of(2020, 8, 24, 15, 38, 42, 0, ZoneId.of("America/Los_Angeles"));
ZonedDateTime startOfDay = given.truncatedTo(ChronoUnit.DAYS);
System.out.println("Truncated to start of day: " + startOfDay);
Instant inUtc = startOfDay.toInstant();
System.out.println("In UTC: " + inUtc);
Output is:
Truncated to start of day: 2020-08-24T00:00-07:00[America/Los_Angeles] In UTC: 2020-08-24T07:00:00Z
Upvotes: 1
Reputation: 18480
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
Upvotes: 1