简体   繁体   中英

the exception with parsing a date YYYY-MM-DD HH:mm:ss

I try to parse a date in the format YYYY-MM-DD HH:mm:ss

String now = "2012-11-02 12:02:00";
DateFormat formatter;
formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date date_temp = (Date) formatter.parse(now.toString());
System.out.println("output: " + date_temp);

It gives me following exception

java.text.ParseException: Unparseable date: "2012-11-02 12:02:00"

Well yes, you've created a formatted with one format ("EEE MMM dd HH:mm:ss z yyyy") and then given it a string in a completely different format to parse. Why did you think that would work? Try this:

// Locale specified to avoid any cultural differences. You may also
// want to specify the time zone.
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                                            Locale.US);
Date date = formatter.parse(now);

Note that the parsed Date does not know anything about formatting - the result of calling toString() (as you're doing implicitly here) is always just the default format, in the JRE default time zone. If you want to print it out with a particular format, use SimpleDateFormat again.

Also note that I've combined declaration and initialization for the variable. Prefer that over declaring a variable in one line and giving it an initial value later.

Of course your date string is not in the format you are using in SimpleDateFormat . So it won't be able to parse it into a date object .

Try using this: -

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

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