javadate-formatting

Java DateFormat not converting correctly


I am probably overlooking something, but parsing from string to date is not working correctly for me. I have String: "20110705_060229" which is format: "YYYYddMM_HHmmss"

this piece of code:

Date triggermoment;

public void setTriggermoment(String triggermoment) throws ParseException {
  DateFormat formatter = new SimpleDateFormat("YYYYddMM_HHmmss");
  this.triggermoment = formatter.parse(triggermoment);
}

gives me as output (when I run toString() method on triggermoment): Mon Jan 03 06:02:29 CET 2011

Why is it not parsing the day's and month's correctly? It should be June 7 instead of Jan 3.

Thanks in advance!


Solution

  • You have to use y for years. Y is used for week year :

    DateFormat formatter = new SimpleDateFormat("yyyyddMM_HHmmss");
    

    Output:

    Sat May 07 06:02:29 CEST 2011
    

    It should be June 7 instead of Jan 3

    The 5th month in the year is may, not june.