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