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
OffsetDateTime.parse( "2011-10-06T12:00:00-08:00" )
.format(
DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( Locale.US ) // Or Locale.CANADA_FRENCH and such.
)
Oct 6, 2011
The modern approach uses the java.time classes that supplant the troublesome old legacy date-time classes.
You input string is in a format that complies with the ISO 8106 standard. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
Parse as an OffsetDateTime
because your input strings includes an offset-from-UTC but not a time zone.
OffsetDateTime odt = OffsetDateTime.parse( "2011-10-06T12:00:00-08:00" ) ;
odt.toString(): 2011-10-06T12:00-08:00
Generate a string in your desired format. Let java.time automatically localize rather than hard-code formatting patterns.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( Locale.US ); // Or Locale.CANADA_FRENCH and such.
String output = odt.format( f );
output: Oct 6, 2011
When seralizing a date-time value as text, use the standard ISO 8601 formats rather than a localized format.
String output = odt.toLocalDate().toString() ;
2011-10-06
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, and more.