tl;dr
LocalDate // Modern class for representing a date-only value without time-of-day and without time zone.
.parse(
"1/23/40" ,
DateTimeFormatter.ofPattern( "M/d/uu" ) // Defaults to century 20xx.
) // Returns a `LocalDate` object.
.toString() // Generate text in standard ISO 8601 format.
2040-01-23
Specify default century
The SimpleDateFormat
class has a setting for what century to assume when parsing an input string with a two-digit century: SimpleDateFormat::set2DigitYearStart
.
But… you should stop using this class.
java.time
That SimpleDateFormat
class is part of the terrible date-time classes bundled with the earliest versions of Java. These classes are now legacy, supplanted entirely by the modern java.time classes defined in JSR 310.
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
➥ This class parses input strings with two-digit years always using the century of 20xx.
String input = "1/23/40" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/uu" ) ;
LocalDate localDate = LocalDate.parse( input , f ) ;
See this code run live at IdeOne.com.
localDate.toString(): 2040-01-23
Tip: I have found the use of 2-digit years to be quite troublesome in business apps. The ambiguity with day-of-month and month makes it easy for misinterpretation and miscommunication. I suggest always using 4-digit years.
This problem is even worse when sharing data across cultures. Then I suggest using ISO 8601 formats for textual date-time values.
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
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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.