skip to Main Content

How can I calculate and format time like HH:mm, Of much time is left before tomorrow? with SimpleDateFormat.

2

Answers


  1. import java.time.LocalDateTime;
    import java.time.LocalDate;
    import java.time.LocalTime;
    import java.time.Duration;
    
    
    LocalDateTime tomorrowMidnight = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT).plusDays(1);        
            
    Duration duration = Duration.between(LocalDateTime.now(), tomorrowMidnight);
    System.out.printf("%d:%d", duration.toHours(), duration.toMinutes()%60);
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search