简体   繁体   English

如何在 Android TimeUnit 中获取经过的时间

[英]How to get Elapsed time in Android TimeUnit

I have a 5 minutes timer.我有一个 5 分钟计时器。 In case i finish 30 seconds its shown 4:30 but i want set 30 seconds.如果我完成 30 秒,则显示为 4:30,但我想设置 30 秒。

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 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 .您可以使用java.time.Duration ,它以ISO-8601 标准为模型,并作为JSR-310 实施的一部分与Java-8一起引入。 With Java-9 some more convenience methods were introduced. Java-9引入了一些更方便的方法。

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: Output:

04:30
04:30

Learn more about the modern date-time API from Trail: Date Time .Trail: Date Time了解有关现代日期时间 API 的更多信息。

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.现在您在 Millis 中拥有两次,您可以轻松地转换和格式化 Minutes:Second 格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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