【问题标题】:Android Dev: Time span past midnight calculationAndroid Dev:午夜后的时间跨度计算
【发布时间】:2012-03-15 01:12:42
【问题描述】:

我正在为 android 开发自动配置文件更改应用程序...这是我在 android 上开发的第二个应用程序,所以不知道 android 开发的所有花里胡哨...

无论如何...我在计算下一次计时器代码应该执行的时间时遇到了一些问题...主要问题是从午夜到第二天的时间...

例如,假设用户创建了一个睡眠配置文件,该配置文件从晚上 10:30 开始,一直持续到第二天早上 8 点……以此为例,执行处于我放置在代码,但是 nextUpdateInterval 设置不正确......我仍在试图弄清楚如何计算/计算跨越到第二天的时间,此时我开始认为我可能会让这个任务过于复杂?有什么建议吗?

这里是sn-p的代码:

    timer.scheduleAtFixedRate( new TimerTask() {
public void run() {
    //..... some code to convert user stored times into proper time formats
    //PM to PM
    if(isFromTimePM == true && isToTimePM == true){

    }//PM to AM
    else if(isFromTimePM == true && isToTimePM == false){
        if(rightNowDate.getTime() >= fromDate.getTime() && rightNowDate.getTime() >= toDate.getTime()){
            foundProfileIndex = i;
                i = profileArrayListSize;


            nextUpdateInterval = rightNowDate.getTime() - toDate.getTime();
        }                   
    }//AM to AM
    else if(isFromTimePM == false && isToTimePM == false){

    }//AM to PM
    else if(isFromTimePM == false && isToTimePM == true){

    }}, 0, nextUpdateInterval);

谢谢, P

【问题讨论】:

    标签: android timer


    【解决方案1】:

    忘记下午和上午。由于您似乎正在使用日期,因此当您使用 getTime() 方法时,您将获得自 Epoch 以来经过的毫秒数。只需减去这两个,您将获得以毫秒为单位的时间间隔:

    long nextUpdateInterval = secondDate.getTime() - firstDate.getTime();
    

    nextUpdateInterval 很长,是“连续任务执行之间的毫秒数”。

    【讨论】:

    • 实际上...AM/PM 如果条件只是为了灵活逻辑以查看“rightNow”时间是否会在用户设定的时间内...如您所见,我完全按照你提到的设置 nextUpdateInterval:nextUpdateInterval = rightNowDate.getTime() - toDate.getTime();....但这不是设置正确的下一次执行时间
    【解决方案2】:

    这个 secondDate - firstDate 都不是必需的,我最终做的是以下内容:

    1. 将所有时间转换为毫秒
    2. 将毫秒转换为日期对象
    3. 使用 compareTo 将 'to' 'from' 日期与当前日期/时间进行比较
    4. 如果我发现配置文件匹配,则我将“到”日期存储为下一次运行日期
    5. 创建了一个以日期为参数的 reScheduleTimer 方法...我只是使用 .schdule(timertask, date) 来重新安排计时器...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 2018-02-04
      • 2012-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多