Nina Gos
Nina Gos

Reputation: 31

How to calculate how much hours have to 00.00 in android with Java

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.

Upvotes: 0

Views: 85

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 339472

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

Upvotes: 1

shmosel
shmosel

Reputation: 50726

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);

Upvotes: 1

Related Questions