3

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.

3 Answers 3

13

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

1
  • OK, got it. I'll post the answer.
    – e-satis
    Jun 22, 2009 at 16:35
5

Thanks to Aaron, the right version :

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

java.time

The existing answers have already explained correctly how java.util.Date returns the year relative to 1900 and how you can get around the problem by using java.util.Calendar.

The question and existing answers use java.util date-time API and SimpleDateFormat which was the correct thing to do in 2009. In Mar 2014, the java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern date-time API. Since then, it is highly recommended to stop using the legacy date-time API.

Using java.time, the modern date-time API:

You do not need a DateTimeFormatter: java.time API is based on ISO 8601 and therefore you do not need a DateTimeFormatter to parse a date-time string which is already in ISO 8601 format e.g. your date string, 2009-06-22 which can be parsed directly into a LocalDate instance which contains just date units.

Demo:

import java.time.LocalDate;

class Main {
    public static void main(String args[]) {
        String strDateTime = "2009-06-22";
        LocalDate date = LocalDate.parse(strDateTime);
        System.out.println(date);
        System.out.printf("Day: %d, Month: %d, Year: %d", date.getDayOfMonth(), date.getMonthValue(), date.getYear());
    }
}

Output:

2009-06-22
Day: 22, Month: 6, Year: 2009

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.