tl;dr
LocalDate.parse(
"20170412" ,
DateTimeFormatter.BASIC_ISO_DATE
).format(
DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
.withLocale( Locale.US )
)
Wednesday, April 12, 2017
Using java.time
The modern way is with the java.time classes, LocalDate
specifically. The LocalDate
class represents a date-only value without time-of-day and without time zone.
Define a formatting pattern to match your input. Your input happens to comply with the “basic” version of ISO 8601 where the use of separators is minimized. For that, java.time has already pre-defined a formatting pattern.
DateTimeFormatter f = DateTimeFormatter.BASIC_ISO_DATE ;
LocalDate ld = LocalDate.parse( "20170412" , f );
To generate a string in standard ISO 8601 format, call toString
. The java.time classes use the standard formats when parsing/generating strings.
String output = ld.toString() ;
2017-04-12
Generally I suggest you stick with the expanded versions of the ISO 8601 formats, as seen in this example above that includes the hyphens in a date, rather than the basic versions. The expanded versions are easier to read by humans and more recognizable as date-time values.
Localize
You can generate strings in other formats. You can specify exact formats if desired. But generally best to let java.time localize for you.
To localize, specify:
FormatStyle
to determine how long or abbreviated should the string be.
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, separators, and such.
Example code.
Locale l = Locale.CANADA_FRENCH ; // Or Locale.US, Locale.ITALY, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
.withLocale( l ) ;
String output = ld.format( f ) ;
For Locale.US
that output would be:
Wednesday, April 12, 2017
About java.time
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?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
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.