Java:GregorianCalendar 返回错误数据
我想计算一年中特定周数的星期一。我是这样做的:
final GregorianCalendar calendar = new GregorianCalendar(Locale.GERMANY);
calendar.clear();
calendar.set(Calendar.YEAR, 2012); // set to 2012
calendar.set(Calendar.WEEK_OF_YEAR, 20); // set to week number 20
calendar.setTimeZone(TimeZone.getTimeZone("Europe/Berlin")); // set time zone
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yy"); // german format
System.out.println(sdf.format(calendar.getTime())); // return date
这必须返回 2012 年 5 月 14 日(德语格式为 14.05.12),但它返回 2012 年 5 月 16 日,但这是错误的。
因此,2012 年的值为 +2,2011 年的值为正确,2010 年的值为 -1。
为什么 GregorianCalendar 计算出错误的日期?
预先感谢并来自德国的问候。
I want to calculate the monday of a specific week number of a year. This is how I do it:
final GregorianCalendar calendar = new GregorianCalendar(Locale.GERMANY);
calendar.clear();
calendar.set(Calendar.YEAR, 2012); // set to 2012
calendar.set(Calendar.WEEK_OF_YEAR, 20); // set to week number 20
calendar.setTimeZone(TimeZone.getTimeZone("Europe/Berlin")); // set time zone
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yy"); // german format
System.out.println(sdf.format(calendar.getTime())); // return date
This has to return the 14th of May 2012 (14.05.12 in german format), but it returns the 16th of May 2012, but this is wrong.
So for 2012 its +2, 2011 is correct and 2010 is -1.
Why does the GregorianCalendar calculate the wrong date?
Thanks in advance and greets from germany.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这取决于 getFirstDayOfWeek() 返回的内容以及 1 月 1 日是哪一天。
来自 Java 文档:
It will depend on what getFirstDayOfWeek() returns and also what day the 1st of January falls on.
From Javadocs:
也尝试设置
DAY_OF_WEEK
:为我返回 14.05.12、16.05.11 和 17.05.10。
编辑:
如果我理解正确的话,你会得到 16.05.10、16.05.11 和 16.05.12,对吗?
这表明日历的一部分被重用。您是否从 2011 年开始连续进行测试?如果是这样,仅更改年份而不使用任何
clear()
等将保留之前计算的日期。Try setting the
DAY_OF_WEEK
, too:Returns 14.05.12, 16.05.11 and 17.05.10 for me.
Edit:
If I understand that correctly, you get 16.05.10, 16.05.11 and 16.05.12, right?
That indicates that part of the calendar is reused. Did you, by any chance, test in a row starting with 2011? If so, changing the year only without any
clear()
etc. would keep the previously calculated date.