ww SimpleDateFormat的奇怪行为 [英] Strange behaviour of ww SimpleDateFormat
问题描述
谁能解释为什么我在尝试解析日期时会得到这些值? 我尝试了三种不同的输入,如下所示:
Can anyone explain why do I get those values while trying to parse a date? I've tried three different inputs, as follows:
1)2013年第三周
1) Third week of 2013
Date date = new SimpleDateFormat("ww.yyyy").parse("02.2013");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.WEEK_OF_YEAR) + "." + cal.get(Calendar.YEAR));
哪个输出:02.2013
(正如我预期的那样)
Which outputs: 02.2013
(as I expected)
2)2013年第一周
2) First week of 2013
Date date = new SimpleDateFormat("ww.yyyy").parse("00.2013");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.WEEK_OF_YEAR) + "." + cal.get(Calendar.YEAR));
哪个输出:52.2012
(这对我很好,因为2013年的第一周也是2012年的最后一个)
Which outputs: 52.2012
(which is fine for me, since the first week of 2013 is also the last one of 2012)
3)2013年第二周
3) Second week of 2013
Date date = new SimpleDateFormat("ww.yyyy").parse("01.2013");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.WEEK_OF_YEAR) + "." + cal.get(Calendar.YEAR));
哪个输出:1.2012
(这对我来说完全没有有意义)
Which outputs: 1.2012
(which makes absolutely no sense to me)
有人知道为什么会这样吗?我需要解析格式为(一年中的一周).(年)的日期.我使用的是错误的模式吗?
Does anyone know why this happens?? I need to parse a date in the format (week of year).(year). Am I using the wrong pattern?
推荐答案
您使用的是ww
,它是一周中的一周的一周",然后是yyyy
,它是日历年",而不是周".年".设置星期几然后设置日历年是解决问题的秘诀,因为它们实际上只是单独的编号系统.
You're using ww
, which is "week of week-year", but then yyyy
which is "calendar year" rather than "week year". Setting the week-of-week-year and then setting the calendar year is a recipe for problems, because they're just separate numbering systems, effectively.
您应该在格式字符串中使用YYYY
来指定星期年份...尽管不幸的是,您似乎无法以理智的方式获取该值. (我希望有一个Calendar.WEEKYEAR
常量,但是没有这样的东西.)
You should be using YYYY
in your format string to specify the week-year... although unfortunately it looks like you can't then get the value in a sane way. (I'd expect a Calendar.WEEKYEAR
constant, but there is no such thing.)
此外,每年的周值从1开始,而不是0 ...,并且在两周的年中没有周.是 是2013年的第一周还是是2012年的最后一周...不是全部.
Also, week-of-year values start at 1, not 0... and no week is in two week-years; it's either the first week of 2013 or it's the last week of 2012... it's not both.
如果可以的话,我个人会避免使用周年和周-它们会非常令人困惑,尤其是当一个日历年中的日期在不同的周年中时.
I would personally avoid using week-years and weeks if you possibly can - they can be very confusing, particularly when a date in one calendar year is in a different week year.
这篇关于ww SimpleDateFormat的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!