0

好吧,我目前正在为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"); 

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

4

2 回答 2

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;
}
于 2011-10-31T18:02:14.913 回答
0

因为它隐式地转换为 long,所以你正在失去一些分钟和小时。

声明diffDays为 double,然后您可以在有时向用户显示,例如2.5 days,它不会显示为2 days. 或者,您可以取整数部分表示天数,然后从分数中计算小时数:

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

这给了你一分钟。只要确保您确实声明diffDays为双精度或浮点数。

于 2011-10-31T18:09:47.360 回答