I have this date that I seem to be unable to parse correctly.
String text \"Wed May 21 05:44:09 -0700 2014\";
This is my date format
public s
OffsetDateTime.parse (
"Wed May 21 05:44:09 -0700 2014" ,
DateTimeFormatter.ofPattern ( "EEE MMM dd HH:mm:ss Z uuuu" , Locale.US )
)
The Answer by Pshemo seems to be correct, specify a Locale to match the data input. But the Question and Answer both use troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
By the way, your input string is in a terrible format. When serializing date-time values to text, use the standard ISO 8601 formats.
First define a formatting pattern to match your input string.
Specify a Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such. If omitted, your JVM’s current default locale is implicitly used. Better to be specify explicitly.
String input = "Wed May 21 05:44:09 -0700 2014";
Locale locale = Locale.US;
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "EEE MMM dd HH:mm:ss Z uuuu" , locale );
Parse as an OffsetDateTime. If we had a time zone we would parse as a ZonedDateTime. But we have only an offset-from-UTC of -0700
in your input string.
OffsetDateTime odt = OffsetDateTime.parse ( input , f );
Dump to console.
System.out.println ( "input: " + input );
System.out.println ( "odt: " + odt );
When run.
input: Wed May 21 05:44:09 -0700 2014
odt: 2014-05-21T05:44:09-07:00
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, andfz more.
To parse your date you can use
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_PATTERN);
Date parsedDate = sdf.parse("Wed May 21 05:44:09 -0700 2014");
But if that fails and you are seeing
java.text.ParseException: Unparseable date: "Wed May 21 05:44:09 -0700 2014"
then most probably Wed
is not recognised by your default locale as correct day. In that case you will have to set locale to place where this word is recognized, like
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_PATTERN, Locale.US);
// ^^^^^^^^^