简体   繁体   中英

How to get Elapsed time in Android TimeUnit

I have a 5 minutes timer. In case i finish 30 seconds its shown 4:30 but i want set 30 seconds.

code to decrease time

String timeReminder= String.format(Locale.ENGLISH , "%02d:%02d" , TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) , TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)) );
            timerText.setText(timeReminder);

i want only reminder time.

java.time

You can use java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation . With Java-9 some more convenience methods were introduced.

import java.time.Duration;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        Duration total = Duration.ofMinutes(5);
        Duration elapsed = Duration.ofSeconds(30);
        Duration remaining = total.minus(elapsed);

        // ###############Java 8###########################
        String timeReminder = String.format(Locale.ENGLISH, "%02d:%02d", remaining.toMinutes(),
                remaining.toSeconds() % 60);
        System.out.println(timeReminder);
        // ################################################

        // ###############Java 9###########################
        timeReminder = String.format(Locale.ENGLISH, "%02d:%02d", remaining.toMinutesPart(), remaining.toSecondsPart());
        System.out.println(timeReminder);
        // ################################################
    }
}

Output:

04:30
04:30

Learn more about the modern date-time API from Trail: Date Time .

Ok, I guess the word you are looking for is elapsed time, however, your logic doesn't seem correct.

So here is the example,

Long startTime = System.currentTimeMillis();
Long estimatedTime = TimeUnit.MINUTES.toMillis(10); // For 10 minutes

To calculate elapsed time:

    Long elapsedTime = System.currentTimeMillis() - startTime;  

To calculate Remaining time:

    Long remainingTime = estimatedTime - System.currentTimeMillis();

Now you have both times in Millis, You can easily convert and format in Minutes:Second format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM