简体   繁体   中英

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!

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.

MM is month whereas mm is munutes. y is for year and Y is used for Week year.

Try yyyyddMM_HHmmss instead of YYYYddMM_HHmmss

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM