两个日期之间的差异,以天,各不相同 [英] Difference between two dates, in days, varies
问题描述
Date d = new Date(today.getTimeInMillis());
Date d1 = new Date(dueDate.getTimeInMillis());
int daysUntil = (int) ((d1.getTime() - d.getTime())/ (1000 * 60 * 60 * 24));
使用上述code,其中今天
设置为00:00在当天日历和的dueDate
设置为00:00我今天比较,从这个我结果不同的日期。
Using the above code, where today
is a calendar set to 00:00 on the current day, and dueDate
is set to 00:00 on the date I am comparing today to, my results from this differ.
有一些是在这里面变化,使我的输出x或X + 1,其中x是正确的答案。
There is something in this which varies, making my output either x or x+1 where x is the correct answer.
什么是这里的问题,我能做些什么,使之更稳定?
What is the issue here, and what can I do to make it more stable?
推荐答案
主要有两个原因,为什么你的code被打破:
- 第二部分或毫秒级(你可能忽略了)
- 夏令效果
我说明和解释的第二个原因。
I demonstrate and explain the second reason.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = sdf.parse("2016-03-20");
Date d2 = sdf.parse("2016-03-28");
int daysUntil = (int) ((d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
System.out.println(daysUntil); // 7 (should be 8)
在code在时区欧洲/柏林运行。由于从冬季时夏令时凌晨2点通过在2016年3月27日快一个小时导致时钟的跳变,有是一个小时失踪。有一天,有只有23小时,24收益率师零点导致计数少一天。
The code was run in timezone "Europe/Berlin". Due to the change from winter time to summer time causing a jump of clocks by one hour forward on 2016-03-27 at 2 am, there is one hour missing. One day has only 23 hours so the division by 24 yields zero resulting in counting one day less.
你可以做什么?
您的解决方法加入1000毫秒的dueDate
听起来好像你已经在你的输入可能忽视三角洲毫秒。这可能解决的一个特例,但通常不足以解决夏令问题,太。无论你选择在 java.util.Date
的基础是或多或少的邪恶黑客攻击。
Your workaround adding 1000 milliseconds to dueDate
sounds as if you have overlooked possible millisecond deltas in your input. This might solve a special case but will usually not be sufficient to solve the daylight saving problem, too. Whatever you choose on base of java.util.Date
it is a more or less an evil hack.
我心目中最好的是为构建的java.util.GregorianCalendar
的实例,并以(的Android系统内置的东西的范围之内)一个接一个陆续添加一天,直到你已经通过了到期日,再算上你有多少天添加即可。不优雅和容易出错,因为不同部位毫秒很容易被忽视这里也。
The best I have in mind (within the scope of Android-built-in stuff) is to construct an instance of java.util.GregorianCalendar
and to add successively one day after one until you have passed the due-date, and then count how many days you have added. Not elegant and errorprone because varying millisecond parts can easily be overlooked here, too.
否则,你可以尝试这项任务的各种外部库。有四个可以在Android可以在一个简单的方法计算出经过天。
Otherwise you can try various external libraries for this task. There are four available on Android which can calculate elapsed days in an easy way.
- Date4J (主要优点:非常小,但其他有限的功能)
- Threeten-ABP (使用Java-8的反向移植)
- 乔达 - 时间的Android (基于乔达时间)
- Time4A (我自己的图书馆为Android )
- Date4J (main advantage: very small but else limited features)
- Threeten-ABP (uses backport of Java-8)
- Joda-Time-Android (based on Joda-Time)
- Time4A (my own library for Android)
这篇关于两个日期之间的差异,以天,各不相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!