skip to Main Content

I’ll create a count timer for my android app. I want to calculate how much time have in 24:00 in hours from current time. I couldn’t not find any solutions and it’s so complicated for me to calculate it with miliseconds.

For Example:

Now time is: 22.55
Have 1 hours and 5 minutes to 00.00

I’ll make count timer with this like:

Remaining: 1 hours 5 Minutes

Anyone can help me?
Thanks a lot.

2

Answers


  1. You can use java.time.Duration to compute the time difference between now and midnight:

    LocalDateTime now = LocalDateTime.now();
    LocalDateTime midnight = LocalDate.now().plusDays(1).atTime(0, 0);
    Duration between = Duration.between(now, midnight);
    System.out.printf("Remaining: %d hours %d minutes",
            between.toHours(), between.toMinutes() % 60);
    
    Login or Signup to reply.
  2. Days are not always 24 hours long

    On some dates in some time zones, the day is not 24 hours long. Some days may run 23, 23.5, 25, or some other number of hours long.

    So let java.time determine the first moment of the following day.

    ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;  // Or ZoneId.systemDefault() ;
    ZonedDateTime zdt = ZonedDateTime.now( z ).with( LocalTime.of( 22 , 55 ) ) ;
    ZonedDateTime firstMomentOfTomorrow = zdt.toLocalDate().plusDays( 1 ).atStartOfDay( z ) ;
    Duration d = Duration.between( zdt , firstMomentOfTomorrow ) ;
    
    System.out.println(
        zdt.toString() + "/" + firstMomentOfTomorrow.toString() + " = " + d.toString() 
    );
    

    See this code run live at IdeOne.com.

    2021-12-28T22:55+09:00[Asia/Tokyo]/2021-12-29T00:00+09:00[Asia/Tokyo] = PT1H5M

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