Reputation: 1952
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"
Upvotes: 2
Views: 7676
Reputation: 1502246
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.
Upvotes: 9
Reputation: 213311
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");
Upvotes: 2