简体   繁体   中英

How to get next day end of day date time from given Instant ? (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?

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();

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM