How to get remaining time of the day in java?

I would like to calculate the time remaining for next day 00:00:00 from the current date time.

For e.g. time difference between 2022-05-07T05:49:41.883807900Z and 2022-05-08T00:00:00Z

Expected answer: 18:10:19 or 65419 (in seconds).

How can I achieve this with efficiently using java 8?

1 answer

  • answered 2022-05-07 07:03 Basil Bourque

    Get current date. Note that a time zone is crucial here, as for any given moment the date varies around the globe by zone.

    ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
    ZonedDateTime now = ZonedDateTime.now( z ) ;
    LocalDate today = now.toLocalDate() ;
    

    Get the first moment of tomorrow. Do not assume the day starts at 00:00. Some dates in some zones start at another time. Let java.time determine the first moment.

    ZonedDateTime startOfTomorrow = today.plusDays( 1 ).atStartOfDay( z ) ;
    

    Calculate elapsed time.

    Duration d = Duration.between( now , startOfTomorrow ) ;
    

    Interrogate the duration for your desired number of whole seconds until tomorrow.

    long secondsUntilTomorrow = d.toSeconds() ;
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum