在Android上计算日期

时间:2011-10-31 17:58:14

标签: android calendar days

我正在为Android构建一个应用程序,我需要存储一天并计算到那一天到来的天数。

我将这一天存储在共享的首选项上。首先,我初始化日历。

         Calendar next = Calendar.getInstance();
         Calendar now = Calendar.getInstance();

然后我设置“下一个”日历

            nday = prefs.getInt("d", 0);
            nmonth = prefs.getInt("m",0);
            nyear = prefs.getInt("y",0);
            next.set(nyear, nmonth, nday);

然后我这样做来计算剩余的天数。

            diff =next.getTimeInMillis()-now.getTimeInMillis();
            diffDays = diff / (24 * 60 * 60 * 1000); 
            output.setText(diffDays + " Days left");

这就是问题所在。计算器工作很好,直到2天前。当它应该说“3天”它写的是“2天”,它仍然有一天错了。如果我尝试关闭并打开应用程序,有时它会计算出正确的日期,有时会错过一天......有人能理解什么是错的吗?我有diff和diffDays一样长。我尝试将它们转换为int但我仍然遇到同样的问题,有时它会写3天,有时候会写2 ....


好的,我发现了如何解决这个问题。似乎getInstance有毫秒差异,所以我做了这个

Calendar now = Calendar.getInstance();
    now.set(Calendar.HOUR_OF_DAY,00); 
    now.set(Calendar.MINUTE ,00);
    now.set(Calendar.SECOND,00);
    now.set(Calendar.MILLISECOND,00);

从共享首选项中获取当天

       nday = extras.getInt("nDay");
       nmonth = extras.getInt("nMonth");
       nyear = extras.getInt("nYear");
       //set the calendar
       next.set(nyear, nmonth, nday, 00, 00,00);
       next.set(Calendar.MILLISECOND,00);  

最后计算差异

    long diff = 0;
    diff = next.getTimeInMillis()-now.getTimeInMillis();
    diffDays = diff / (24 * 60 * 60 * 1000);
    output.setText(diffDays + " Days"); 

现在我得到了真正的区别,没有任何错误,感谢大家的帮助!

2 个答案:

答案 0 :(得分:0)

还可以使用日历计算日期。

Calendar diff = Calendar.getInstance();
long diffMillis = next.getTimeInMillis()-now.getTimeInMillis();
diff.setTimeInMilliSeconds(Math.abs(diffMillis));
int days = diff.get(Calendar.DAY_OF_YEAR);

if (diffMillis < 0L) {
  days *= -1;
}

答案 1 :(得分:0)

因为它隐含了很长时间,所以你会失去一些分钟和小时。

diffDays声明为double,然后您可以向用户显示,例如2.5 days,并且不会将其显示为2 days。或者,您可以获取天数的整数部分,并从分数计算小时:

int hour = (diffDays - Math.floor(diffDays))*24

这给你一分钟。只需确保您将diffDays声明为double或float。