I am trying to parse datetime string with SimpleDateFormat.parse()
but I keep receiving Unparseable date exceptions.
Here is the date format I am trying to parse: 2011-10-06T12:00:00-08:00
Here is the code I am using:
try {
String dateStr = "2011-10-06T12:00:00-08:00";
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
SimpleDateFormat dateFormatter = new SimpleDateFormat("MMM d, yyyy");
Date date = dateParser.parse(dateStr);
System.out.println(dateFormatter.format(date));
} catch(Exception e) {
System.out.println(e.getMessage());
}
Which returns this error: java.text.ParseException: Unparseable date: "2011-10-06T12:00:00-08:00"
As far as I know this is the correct way to use the SimpleDateFormat class but I'm not fluent in Java so I could be mistaken. Any one know what my issue is?
You first need to format the value in
"2011-10-06T12: 00: 00-08: 00"
.After, create the formating for formataction desired. Ex:
SimpleDateFormat fmt = new SimpleDateFormat ("dd / MM / yyyy HH: mm: ss");
and after make parse for date. Ex:
Date date = dateParser.parse (dateFormat);
and print of date formated.Below, one complete example.
For a date format like
2013-06-28T00:00:00+00:00
, this code should work:Try with
I'd strongly recommend using JodaTime for this sort of thing.
You're trying to parse an ISO Date format, and Joda does that 'out of the box', and will give you plenty of other benefits too.
I long ago gave up trying to get the standard JDK data classes to do helpful things.
I am sure most of you got frustrated from the fact that SimpleDateFormat can not handle ISO8601 format. Here is my little trick to solve this nuisance.
Create a list of Know format you know that you will use for your application and apply SimpleDateFormat to the list. Now, in your formatDate() method, simple try all your known format and trap the Exception, then if still did not have a date, just use
to try it and see if that work. For more info Simple trick to convert Date format with timezone in Java!
I believe that SimpleDateFormat will not parse timezones with a colon in them (-08:00). It should be able to parse the date
2011-10-06T12:00:00-0800
.Some simple string manipulation should help you get rid of the colon.