Reputation: 4623
How can I parse this date format Mon May 14 2010 00:00:00 GMT+0100 (Afr. centrale Ouest)
to this date format 05-14-2010
I mean mm-dd-yyyy
it's telling me this error :
java.text.ParseException: Unparseable date: "Mon May 14 2010 00:00:00 GMT+0100 (Afr. centrale Ouest)"
EDIT
SimpleDateFormat formatter = new SimpleDateFormat("M-d-yyyy");
newFirstDate = formatter.parse(""+vo.getFirstDate()); //here the error
Thanks in advance!
Upvotes: 2
Views: 1227
Reputation: 200296
This code first adapts the string a bit and then goes on to parse it. It respects the timezone, just removes "GMT" because that's how SimpleDateFormat
likes it.
final String date = "Mon May 14 2010 00:00:00 GMT+0100 (Afr. centrale Ouest)"
.replaceFirst("GMT", "");
System.out.println(
new SimpleDateFormat("MM-dd-yyyy").format(
new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z").parse(date)));
Prints:
05-14-2010
Bear in mind that the output is also timezone-sensitive. The instant defined by your input string is being interpreted in my timezone as belonging to the date that the program printed. If you just need to transform "May 14 2010" into "05-14-2010", that's another story and SimpleDateFormat
is not well suited for that. The JodaTime
library would handle that case much more cleanly.
Upvotes: 5
Reputation: 2223
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test
{
public static void main( String args[] ) throws ParseException
{
// Remove GMT from date string.
String string = "Mon May 14 2010 00:00:00 GMT+0100 (Afr. centrale Ouest)".replace( "GMT" , "" );
// Parse string to date object.
Date date = new SimpleDateFormat( "EEE MMM dd yyyy HH:mm:ss Z" ).parse( string );
// Format date to new format
System.out.println( new SimpleDateFormat( "MM-dd-yyyy" ).format( date ) );
}
}
Outputs:
05-13-2010
Upvotes: 2