Why don't I get the year right using SimpleDateFormat in java?

丶灬走出姿态 提交于 2019-12-11 01:07:00

问题


I trying to parse a data in a MySql Format, I ran across SimpleDateFormat. I can get the proper day and month, but I got a strange result for the year :

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());

Outputs :

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

I tried changing the format to YYYY-MM-dd (got an error) and yy-MM-dd (did nothing). I am programming on Android, don't know if it's important.

For now, I bypass that using a split, but it's dirty and prevent me from using i18n features.


回答1:


The year is relative to 1900. That's a "feature" of the Date class. Try to use Calender.




回答2:


Thanks to Aaron, the right version :

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


来源:https://stackoverflow.com/questions/1028139/why-dont-i-get-the-year-right-using-simpledateformat-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!