Java日历中的错误/ 2010年10月2日的日期? [英] Bug in Java Calendar / Date for 2nd October 2010?

查看:125
本文介绍了Java日历中的错误/ 2010年10月2日的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道我在做错什么,但是我有一段代码可以计算两个日期之间的天数,看起来像下面这样:

  final Calendar first = new GregorianCalendar(2010,Calendar.OCTOBER,1); 
final Calendar last = new GregorianCalendar(2010,Calendar.NOVEMBER,1);

final long difference = last.getTimeInMillis() - first.getTimeInMillis();
final long days =差异/(1000 * 60 * 60 * 24);

System.out.println(difference:+ difference);
System.out.println(days:+ days);总而言之,上面的代码块计算了2010年10月1日至2010年11月1日之间的天数。

我希望看到它返回31天(看到10月份有31天)

 差异:xxxx 
天:31

,而是在10月份显示30天!

 差异:2674800000 
天:30


$ b $我已经设法将其缩小到2010年10月2日至2010年10月3日的日期,似乎只有82800000毫秒,而不是完整的86400000毫秒(缺少一小时)。有没有人有任何想法我在做错什么?/ p>

或者是10月2日是特定日期,比一般日子少一分钟?

解决方案

86400000 - 82800000)/ 1000 = 3600 ,这是一个小时。你看到夏令时,加上整数数学的四舍五入



你可以通过使用浮点数进行计算,最后舍入,或您可以查看像 Joda时间这样的图书馆,它提供比内置的更好的日期数学。 p>

I'm not sure what I'm doing wrong, but I've got a piece of code which calculates the number of days between two dates, and which looks something like the following:

final Calendar first = new GregorianCalendar(2010, Calendar.OCTOBER, 1);
final Calendar last = new GregorianCalendar(2010, Calendar.NOVEMBER, 1);

final long difference = last.getTimeInMillis() - first.getTimeInMillis();
final long days = difference / (1000 * 60 * 60 * 24);

System.out.println("difference: " + difference);
System.out.println("days: " + days);

To summarise, the code block above calculates the number of days between 1st October 2010 and 1 November 2010. I'm expecting to see it return 31 days (seeing as there's 31 days in October)

difference: xxxx
days: 31

but instead it's showing 30 days in October!

difference: 2674800000
days: 30

I've managed to narrow it down to between the the dates 2 October 2010 and 3 October 2010, which seems to only have 82800000 milliseconds, instead of a full 86400000 milliseconds (exactly one hour missing).

Does anyone have any ideas what I'm doing wrong? Or is the 2nd October a special date which has one minute less than a regular day?

解决方案

(86400000 - 82800000)/1000 = 3600, which is one hour. You're seeing daylight savings time, combined with the rounding of integer math

You could get around it by doing the calculations with floating point numbers and rounding at the end, or you could check out a library like Joda time which offers much better date math than what's built in.

这篇关于Java日历中的错误/ 2010年10月2日的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆