[英]Calendar's GregorianCalendar methods setting date to previous day
I'm having a strange issue with abstract Calendar class using the GregorianCalendar method. 使用GregorianCalendar方法的抽象Calendar类出现一个奇怪的问题。
For some reason using "calendar.set" is returning a date from the previous day. 由于某些原因,使用“ calendar.set”返回前一天的日期。 See code below for example with comments on where it works fine, and where it goes wrong.
例如,请参见下面的代码,并在其中指出哪些地方可以正常工作以及哪里出了问题。
private Date checkDate(Date d, int hour, int minute, int sec, int milliSec)
{
// Test values for arguments
d = "Wed Apr 06 00:00:00 BST 2011";
hour = minute = sec = milliSec = 0;
Calendar calendar = new GregorianCalendar(sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]);
calendar.setTime(d);
// *** OK *** calendar.getTime() will display correctly here (Wed Apr 06 00:00:00 BST 2011)
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, sec);
calendar.set(Calendar.MILLISECOND, milliSec);
// *** NOT OK *** calendar.getTime() will display inncorrectly here (Tue Apr 05 01:00:00 BST 2011)
return calendar.getTime();
} Any ideas? } 有任何想法吗?
Thanks 谢谢
Calendar calendar = new GregorianCalendar(sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]);
calendar.setTime(d);
Ok, so you have a calendar with its timezone set to UTC and set its time to 好的,所以您有一个日历,其时区设置为UTC并将其时间设置为
Wed Apr 06 00:00:00 BST 2011
. Wed Apr 06 00:00:00 BST 2011
。
Internally, this is mapped to 在内部,这映射到
2011-04-05 23:00:00 UTC
(the date and time is adopted, the time zone is kept). 2011-04-05 23:00:00 UTC
(采用日期和时间,保留时区)。
Setting the hour, minute, second and millisecond fields of the calendar to 0 will change it to 将日历的时,分,秒和毫秒字段设置为0会将其更改为
2011-04-05 00:00:00 UTC
. 2011-04-05 00:00:00 UTC
。
If you now convert the calendar to a java.util.Date
object and print it while considering your local time zone (BST), the output will be: 如果现在将日历转换为
java.util.Date
对象并在考虑本地时区(BST)的情况下进行打印,则输出将为:
2011-04-05 01:00:00 BST
. 2011-04-05 01:00:00 BST
。
Calendar is a bit strange, as you can read in its javadoc; 日历有点奇怪,因为您可以在其javadoc中阅读; the bottom line is that you have to call calendare.get() after every time you call a calendar.set(...) or the modification may be inconsistent.
最重要的是,您必须在每次调用calendar.set(...)之后都调用calendare.get(),否则修改可能会不一致。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.