0

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?

6
  • 1
    Anything you've tried to solve it?
    – ernest_k
    May 7, 2022 at 5:57
  • 1
    Does this answer your question? Java Calculate time until event from current time
    – hfontanez
    May 7, 2022 at 6:14
  • 1
    Assuming that now is a ZonedDateTime representing the current date and time in your time zone, you may get the remaining time of the day from Duration.between(now, now.toLocalDate().plusDays(1).atStartOfDay(now.getZone())). You may search for how to format the resulting Duration object in a nice and human-readable way. Or simply convert to seconds by calling its toSeconds method.
    – Ole V.V.
    May 7, 2022 at 6:42
  • 1
    @Slaw With now.plusDays(1) you would additionally need .truncatedTo(ChronoUnit.DAYS). It would work, I think, but there are some corner cases around the day not always starting at 00:00:00 in all time zones that we’d need to think through.
    – Ole V.V.
    May 7, 2022 at 6:45
  • I think the precise result in your example would be 18:10:18.1161921. Do you want the result rounded up always?
    – Ole V.V.
    May 7, 2022 at 6:49

1 Answer 1

3

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() ;
1
  • For how to format the obtained Duration like 18:10:19 you may see my answer here or search for other similar answers.
    – Ole V.V.
    May 7, 2022 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.