如何在Java中将此字符串“03:34:21”转换为秒

时间:2015-08-15 07:48:58

标签: java android

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

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

在onPause中我在SharedPreferences中记录tvTimer的值为String,例如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的值为String,例如00:21:13(21分13秒)和onPause发生的时间

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

1 个答案:

答案 0 :(得分:4)

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

使用:拆分字符串,然后获取每个值并转换为秒。我用粗体标出了这些线条。希望这很有帮助