Issue
How can I calculate and format time like HH:mm, Of much time is left before tomorrow? with SimpleDateFormat.
Solution
SimpleDateFormat and related legacy classes were years ago supplanted by the modern java.time classes defined in JSR 310.
Determining “tomorrow” requires a time zone. Days start earlier as you move eastward through time zones.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
Capture the current moment as seen through that time zone.
ZonedDateTime now = ZonedDateTime.now( z ) ;
Now we are in a position to determine “tomorrow”, specifically the first moment of the following day.
Extract the date portion.
LocalDate today = now.toLocalDate() ;
LocalDate tomorrow = today.plus( 1 ) ;
Get first moment. Note that we do not assume the day starts at 00:00 🕛. Some dates in some zones start at a different time of day, such as 01:00 🕐. Let java.time determine the first moment.
ZonedDateTime startTomorrowTokyo = tomorrow.atStartOfDay( z ) ;
Calculate time to elapse.
Duration untilTomorrow = Duration.between ( now , startTomorrowTokyo ) ;
Generate text in standard ISO 8601 format.
String output = untilTomorrow.toString() ;
If you insist on the risky ambiguous use of clock-time to represent the duration, you can build your own string by interrogating the Duration object. Call its to…Part methods.
Answered By - Basil Bourque
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.