gpt4 book ai didi

java - 如何在Java中将此字符串 "03:34:21"转换为秒

转载 作者:行者123 更新时间:2023-12-01 18:12:22 24 4
gpt4 key购买 nike

在我的应用程序中,我有一个计时器,每秒更新一个 TextView,格式如下:

00:00:00 - hours, minutes, seconds.

在onPause中,我在SharedPreferences中将tvTimer的值记录为字符串,例如00:21:13(21分13秒)以及onPause发生的时间

在 onResume 中,我获取了这些值,并尝试将现在和上一个 onPause 之间的时间添加到 tvTimer 字符串的值中,您可以在 TODO 中看到这一点,但我不知道该怎么做。

private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;

private void startTimer() {
tvTimer.setVisibility(View.VISIBLE);
tvTimer.setText(obtainTimerProgress());

startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}

private Runnable updateTimerThread = new Runnable() {

public void run() {

timeInMilliseconds = SystemClock.uptimeMillis() - startTime;

updatedTime = timeSwapBuff + timeInMilliseconds;

int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;

int hours = mins / 60;

tvTimer.setText(String.format("%02d", hours) + ":" + String.format("%02d", mins) + ":" + String.format("%02d", secs));
customHandler.postDelayed(this, 0);
// TODO Find a suitable moment to customHandler.removeCallbacks
}

};

private String obtainTimerProgress() {
SharedPreferences preferences = getActivity().getSharedPreferences(Constant.USER_PREFERENCES, Activity.MODE_PRIVATE);
String timerProgress = preferences.getString(Constant.PROGRESS + getUserId(), "00:00:00");
if (timerProgress != null && !timerProgress.contentEquals("") && !timerProgress.contentEquals("00:00:00")) {
long timeOfTimerPause = preferences.getLong(Constant.TIME_OF_ON_PAUSE + getUserId(), 0);
long now = new Date().getTime();
long differenceBetweenThenAndNow = (now - timeOfTimerPause ) / 1000;
// TODO Parse the string "00:43:34" and turn it into seconds, add differenceBetweenThenAndNow and format it as "00:53:22" again
}
return timerProgress;
}

在onPause中,我在SharedPreferences中将tvTimer的值记录为字符串,例如00:21:13(21分13秒)以及onPause发生的时间

在 onResume 中,我获取了这些值,并尝试将现在和上一个 onPause 之间的时间添加到 tvTimer 字符串的值中,您可以在 TODO 中看到这一点,但我不知道该怎么做。

最佳答案

public class HelloWorld{     public static void main(String []args){        String time = "1:02:59";        String timeSplit[] = time.split(":");        int seconds = Integer.parseInt(timeSplit[0]) * 60 * 60 +  Integer.parseInt(timeSplit[1]) * 60 + Integer.parseInt(timeSplit[2]);        System.out.println(seconds);     }}

使用 : 分割字符串,然后获取每个值并转换为秒。我已将这些行标记为粗体。希望这对您有帮助

关于java - 如何在Java中将此字符串 "03:34:21"转换为秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32022660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com