I have an Instant Date, eg: 2020-03-09T20:13:57.089Z
and I want to find the end of next day in Instant, eg - 2020-03-10T23:59:59.089Z
(this would be the end of next day compared to the initial date)
How do I do this using Instant in Java?
I have an Instant Date, eg: 2020-03-09T20:13:57.089Z
and I want to find the end of next day in Instant, eg - 2020-03-10T23:59:59.089Z
(this would be the end of next day compared to the initial date)
How do I do this using Instant in Java?
One way is converting Instant
to ZonedDateTime
with UTC
timezone and modify the date as per requirement and then convert it back
Midday :
Instant result = instant.atOffset(ZoneOffset.UTC)
.plusDays(1).with(LocalTime.of(11,59,59,instant.getNano()))
.toInstant();
End of day :
Instant result = instant.atOffset(ZoneOffset.UTC)
.plusDays(1).with(LocalTime.of(23,59,59,instant.getNano()))
.toInstant();
atOffset()
instead of atZone()
. –
Radiotelephone If you want the actual midnight (00:00), you can use:
instant.plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.DAYS);
Otherwise, another solution would be:
LocalDateTime ldt1 = LocalDateTime.ofInstant(instant.plus(1, ChronoUnit.DAYS), ZoneId.systemDefault());
ldt1 = ldt1
.withHour(23)
.withMinute(59)
.withSecond(59);
Instant result = ldt1.atZone(ZoneId.systemDefault()).toInstant();
ldt1.withHour(23).withMinute(59).withSecond(59)
, I think ldt1.toLocalDate().atTime(23, 59, 59)
would be better, because it resets fractional seconds to 0, and it has fewer intermediate objects. –
Radiotelephone LocalDateTime
must be done with UTC time zone, otherwise the resulting time will not be 23:59:59Z
–
Radiotelephone One way is converting Instant
to ZonedDateTime
with UTC
timezone and modify the date as per requirement and then convert it back
Midday :
Instant result = instant.atOffset(ZoneOffset.UTC)
.plusDays(1).with(LocalTime.of(11,59,59,instant.getNano()))
.toInstant();
End of day :
Instant result = instant.atOffset(ZoneOffset.UTC)
.plusDays(1).with(LocalTime.of(23,59,59,instant.getNano()))
.toInstant();
atOffset()
instead of atZone()
. –
Radiotelephone © 2022 - 2024 — McMap. All rights reserved.
11:59:59.089Z
, which is noon, so which is it? --- 2) Is it a requirement to retain the.089
milliseconds like you showed? If so, you should explicitly say so, to clarify your requirements. – Radiotelephone2020-03-10T11:59:59.089Z
(this would be the end of next day)" I have never thought of noon (aka "midday") as being the "end of day" for anything. Are you sure you didn't mean23:59:59
? – Radiotelephone