Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ZonedDateTime to end of the day [duplicate]

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

like image 783
Amit Kumar Avatar asked Nov 15 '19 12:11

Amit Kumar


People also ask

How do I get end of the day from ZonedDateTime?

If you want the last second of the day, you can use: ZonedDateTime eod = zonedDateTime. with(LocalTime. of(23, 59, 59));

How do you get day from ZonedDateTime?

The getDayOfWeek() method of a ZonedDateTime class is used to get the day-of-week field from this ZonedDateTime, which is an enum DayOfWeek. Additional information can be obtained from the DayOfWeek. This includes textual names of the values. Parameters: This method does not take any parameters.

Should I use OffsetDateTime or ZonedDateTime?

Use OffsetDateTime to store unique instants in the universal timelines irrespective of the timezones, such as keeping the timestamps in the database or transferring information to remote systems worldwide. Use ZonedDateTime for displaying timestamps to users according to their local timezone rules and offsets.

Is ZonedDateTime a UTC?

A ZonedDateTime represents a date-time with a time offset and/or a time zone in the ISO-8601 calendar system. On its own, ZonedDateTime only supports specifying time offsets such as UTC or UTC+02:00 , plus the SYSTEM time zone ID.


2 Answers

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).

like image 132
assylias Avatar answered Sep 21 '22 21:09

assylias


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);
like image 36
Fabien Avatar answered Sep 25 '22 21:09

Fabien