计时器显示负值

cnh2zyt3  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(616)

我正在用计时器显示时差。
初始时间保存到SharedReferences:01:11:59 am
然后我得到当前时间:

simpleDateFormat.format(new Date());

输出为:05:19:03 am
2的时差应为4小时左右,但计时表显示:-691.33.46
代码:

Date date1 = simpleDateFormat.parse(initialTimeOnSharedPrefs);
Date date2 = simpleDateFormat.parse(currentTime);

long millis = date2.getTime() - date1.getTime();

chronometer.setBase(SystemClock.elapsedRealtime() - millis);
chronometer.start();

我怎样才能避免负值和得到正确的时间设置到计时器?

zwghvu4y

zwghvu4y1#

为了避免这样的意外,我建议您使用现代日期时间api。

import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String initialTimeOnSharedPrefs = "01:11:59 AM";
        LocalTime startTime = LocalTime.parse(initialTimeOnSharedPrefs,
                DateTimeFormatter.ofPattern("h:m:s a", Locale.ENGLISH));
        LocalTime now = LocalTime.now();
        Duration duration = Duration.between(startTime, now);
        // The model is of a directed duration, meaning that the duration may be
        // negative. If you want to show the absolute difference, negate it
        if (duration.isNegative()) {
            duration = duration.negated();
        }

        // Display duration in its default format i.e. the value of duration#toString
        System.out.println(duration);

        // #################### Since Java-8 ####################
        String formattedDuration = String.format("%d:%d:%d", duration.toHours(), duration.toMinutes() % 60,
                duration.toSeconds() % 60);
        System.out.println("Duration is " + formattedDuration);
        // ######################################################

        // #################### Since Java-9 ####################
        formattedDuration = String.format("%d:%d:%d", duration.toHoursPart(), duration.toMinutesPart(),
                duration.toSecondsPart());
        System.out.println("Duration is " + formattedDuration);
        // ######################################################
    }
}

输出:

PT13H47M39.003708S
Duration is 13:47:39
Duration is 13:47:39

检查 Duration#toString 和isoşu8601şdurations,了解有关isoşu8601格式的更多信息 Duration .
使用传统api的正确方法:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws ParseException {
        String initialTimeOnSharedPrefs = "01:11:59 AM";
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH);
        String strTimeNow = sdf.format(Calendar.getInstance().getTime());
        System.out.println(strTimeNow);

        Date startTime = sdf.parse(initialTimeOnSharedPrefs);
        Date endTime = sdf.parse(strTimeNow);
        long duration = Math.abs(endTime.getTime() - startTime.getTime());

        long seconds = duration / 1000 % 60;
        long minutes = duration / (60 * 1000) % 60;
        long hours = duration / (60 * 60 * 1000) % 24;

        String formattedDuration = String.format("%d:%d:%d", hours, minutes, seconds);
        System.out.println("Duration is " + formattedDuration);
    }
}

输出:

02:53:39 PM
Duration is 13:41:40

一些重要注意事项:

api的日期时间 java.util 以及它们的格式化api, SimpleDateFormat 过时且容易出错。建议完全停止使用它们,并切换到现代日期时间api。出于任何原因,如果您必须坚持使用Java6或Java7,您可以使用threeten backport,它将大部分java.time功能向后移植到Java6和Java7。如果您正在为一个android项目工作,并且您的android api级别仍然不符合java-8,请检查通过desugaring提供的java8+api以及如何在android项目中使用threetenabp。
从trail:date-time了解现代日期时间api。

相关问题