好吧,我目前正在为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");
现在我得到了真正的区别,没有任何错误,谢谢大家的帮助!