views:

316

answers:

2

I trying to parse a data in a MySql Format, I ran accross 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.

+10  A: 

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

Aaron Digulla
Ok, thanks, but how can I parse a date using calender ?
e-satis
OK, got it. I'll post the answer.
e-satis
+4  A: 

Thanks to Aaron, the right version :

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