'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?
Solution 1:[1]
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() ;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Basil Bourque |
