Bite code
Bite code

Reputation: 596623

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

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.

Upvotes: 3

Views: 3467

Answers (3)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 78965

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.

Upvotes: 1

Bite code
Bite code

Reputation: 596623

Thanks to Aaron, the right version :

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

Upvotes: 5

Aaron Digulla
Aaron Digulla

Reputation: 328546

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

Upvotes: 13

Related Questions