Convert ZonedDateTime to end of the day [duplicate]
Asked Answered
V

2

9

In this code,

Instant i = Instant.ofEpochMilli(inputDate);
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instance, ZoneId.of(marketplaceIdToZoneMap.get(timeZone)));

I just want this time zoneDateTime to be end of the day,

like if value of zonedDateTime is : 2019-11-14 12:00:99

Output should come as 2019-11-14 23:59:59

Vienne answered 15/11, 2019 at 12:25 Comment(1)
Not only has this question been asked before, it has also been answered with some very good answers. Please check the link to the original question.Bayle
C
18

If you want the last second of the day, you can use:

ZonedDateTime eod = zonedDateTime.with(LocalTime.of(23, 59, 59));

If you want the maximum time of the day, you can use:

ZonedDateTime eod = zonedDateTime.with(LocalTime.MAX);

Note that there are weird situations where 23:59:59 may not be a valid time for a specific day (typically historical days with complicated timezone changes).

Cardamom answered 15/11, 2019 at 14:24 Comment(0)
F
6

A simple solution is to manually set the values you want:

zonedDateTime.withHour(23).withMinute(59).withSecond(59);

Another solution could be to reset the hours/minutes/second, add one day, and remove one second:

zonedDateTime.truncatedTo(ChronoUnit.DAYS).plusDay(1).minusSecond(1);
Fredrickafredrickson answered 15/11, 2019 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.