为什么我不能在java中使用SimpleDateFormat来获得正确的年份?

时间:2009-06-22 16:24:34

标签: java android simpledateformat date-parsing

我尝试以MySql格式解析数据时遇到了SimpleDateFormat。我可以得到正确的日期和月份,但我今年得到了一个奇怪的结果:

date = 2009-06-22;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
Date d = sdf.parse(date);
System.println(date);
System.println(d.getDate());
System.println(d.getMonth());
System.println(d.getYear());

输出:

2009-06-22
22           OK
5            Hum... Ok, months go from 0 to 11
109          o_O WTF ?

我尝试将格式更改为YYYY-MM-dd(出错)和yy-MM-dd(什么也没做)。我在Android上编程,不知道它是否重要。

现在,我使用拆分绕过它,但它很脏并且阻止我使用i18n功能。

2 个答案:

答案 0 :(得分:12)

这一年是相对于1900年。这是Date类的“特征”。尝试使用Calender

答案 1 :(得分:5)

感谢Aaron,正确的版本:

Calendar c = Calendar.getInstance(); 
c.setTime(sdf.parse(date));
System.println(c.get(Calendar.YEAR));
相关问题