tl;dr
LocalDate.parse( // Represent a date-only value with a date-only class.
"2014-10-04" // Inputs in standard ISO 8601 format are parsed by default. No need to specify a formatting pattern.
) // Returns a `LocalDate` object. Do not conflate a date-time object with a String that represents its value. A `LocalDate` has no “format”.
.format( // Generate a String representing the `LocalDate` object’s value.
DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) // Define your custom formatting pattern. Specify `Locale` for human language and cultural norms used in localization.
) // Return a String.
java.time
The modern approach uses java.time classes that supplanted the troublesome old legacy date-time classes such as Date
/Calendar
/SimpleDateFormat
.
Use a date-only class for date-only values, rather than a date+time class. The LocalDate
class represents a date-only value without time-of-day and without time zone.
Your input string happens to comply with standard ISO 8601 format. The java.time classes use ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.
String input = "2014-10-04" ;
LocalDate ld = LocalDate.parse( input ) ; // No need to specify a formatting pattern for ISO 8601 inputs.
To generate a string representing the LocalDate
object’s value in a particular format, define the formatting pattern. Specify a Locale
object to determine the human language and cultural norms used in localizing.
Locale locale = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , locale ) ;
String output = ld.format( f ) ;
04-Oct-2014
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.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
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.