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?

ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • 1
    Anything you've tried to solve it? – ernest_k May 07 '22 at 05:57
  • 1
    Does this answer your question? [Java Calculate time until event from current time](https://stackoverflow.com/questions/36042954/java-calculate-time-until-event-from-current-time) – hfontanez May 07 '22 at 06: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 07 '22 at 06: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 07 '22 at 06: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 07 '22 at 06:49
  • @OleV.V. That makes sense. (the reason I deleted my comment was because I noticed `#atStartOfDay(ZoneId)` only existed for `LocalDate` and not `ZonedDateTime`, so I figured that was the main reason) – Slaw May 07 '22 at 06:55

1 Answers1

4

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() ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • For how to format the obtained `Duration` like `18:10:19` you may see [my answer here](https://stackoverflow.com/a/44343699/5772882) or search for other similar answers. – Ole V.V. May 07 '22 at 11:50