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.

Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41
Bite code
  • 578,959
  • 113
  • 301
  • 329

3 Answers3

13

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

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
5

Thanks to Aaron, the right version :

Calendar c = Calendar.getInstance(); 
c.setTime(sdf.parse(date));
System.println(c.get(Calendar.YEAR));
Giru Bhai
  • 14,370
  • 5
  • 46
  • 74
Bite code
  • 578,959
  • 113
  • 301
  • 329
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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110