如何从特定日期开始算起计时器?

时间:2019-04-23 11:28:14

标签: android chronometer android-timer

在我的应用程序用户中,从日期和时间选择器(从过去的日期)中选择一个日期和时间,然后我想从该日期启动一个递增计时器,因此我需要在服务中运行它,以便在我的应用程序中被杀死,计时器不会停止。 我已经尝试了Chronometer和stackOverFlow上的一些类似解决方案,但是没有得到任何正确的解决方案。

请检查以下图片,它与我需要的内容非常相似:

https://ibb.co/rFz24kg

1 个答案:

答案 0 :(得分:1)

要获取日期差(此处date2可以是用户指定的日期,而date1可以是当前日期时间(可以通过调用:new Date()获得)) :

public static String getDifferenceBetweenDates(Date date1, Date date2) {
    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

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

    long elapsedDays = difference / daysInMilli;
    difference = difference % daysInMilli;

    long elapsedHours = difference / hoursInMilli;
    difference = difference % hoursInMilli;

    long elapsedMinutes = difference / minutesInMilli;
    difference = difference % minutesInMilli;

    long elapsedSeconds = difference / secondsInMilli;

    return String.format("%s days %s hours %s minutes %s seconds", elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);
}

现在,一旦获得差价,您就可以将this用作递增计时器,并定义 onTick(),以每mCountUpInterval个时间间隔(在CountUpTimer类)

相关问题