我目前正在尝试确定两个日期之间的时间量(其中一个是当前日期/时间,另一个是任意未来日期)。我只使用原生Java和Android API,但我遇到GregorianCalendar的一些问题。到目前为止,我的代码可以在下面看到,但我遇到的问题是两个日期之间的时间非常不准确。你可以看到我在这个例子中将未来的日期设定为圣诞节,但是它告诉我那之前有62天以上,这显然是错误的。
I'm currently trying to determine the amount of time between two dates (one of which is the present date/time, the other an arbitrary future date). I'm using native Java and the Android API only, but I'm having a few problems with GregorianCalendar. My code so far can be seen below, but the problem I'm having is that the time between the two dates is massively inaccurate. As you'll be able to see I've set the future date as Christmas day in this example, but it's telling me there's over 62 days until then, which is clearly wrong.
date = new GregorianCalendar(); currentTime = date.getTimeInMillis(); calendar = new GregorianCalendar(); calendar.set(2011, 12, 25, 0, 0, 0); long difference = calendar.getTimeInMillis()-currentTime; long x = difference / 1000; seconds = x % 60; x /= 60; minutes = x % 60; x /= 60; hours = x % 24; x /= 24; days = x;调试时我添加了date.set(2011,11,23,13,1,15);哪个更准确,但是当我相信正确的天数是31时,它仍然显示32天。
While debugging I added date.set(2011, 11, 23, 13, 1, 15); which was much more accurate, but it still displayed 32 days when I believe the correct amount of days is 31.
非常感谢您的任何帮助,非常感谢。
Thanks very much in advance for any help, much appreciated.
推荐答案代码中的问题是方法 calendar.set(2011,12,25,0) ,0,0); 你想要的是 calendar.set(2011,11,25,0,0,0);
the problem in your code is the method calendar.set(2011, 12, 25, 0, 0, 0); what you want is calendar.set(2011, 11, 25, 0, 0, 0);
您也可以使用 Calendar.DECEMBER 。
javadoc对于这种方法很清楚:
The javadoc is clear for this method:
- @param月用于设置 MONTH calendar 字段。 *月值为0。例如,1表示0。
- @param month the value used to set the MONTH calendar field. * Month value is 0-based. e.g., 0 for January.
更多推荐
如何确定Java之间的现在和任意未来日期之间的时间
发布评论