No such thing as formatted date
A date-time value stored in a date-time class has no format.
A date-time object can generate a String object whose text is in a certain format to represent the date-time’s value. But the String and the date-time are separate and distinct from one another.
java.time
The LocalDate
class represents a date-only value, without time-of-day and without time zone.
A time zone is crucial in determining a LocalDate
. For any given moment, the date varies around the globe by time zone. For example, a few minutes after midnight is still “yesterday” in Montréal.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
Avoid using the troublesome old date-time classes such as java.util.Date and java.util.Calendar. Use only java.time classes.
Convert from GregorianCalendar
If you have a GregorianCalendar
object, convert to a ZonedDateTime
by calling the new method added to the old class, toZonedDateTime
.
ZonedDateTime zdt = myGregCal.toZonedDateTime();
From there get a LocalDate
. The ZonedDateTime object’s own assigned time zone is used to determine that date.
LocalDate localDate = zdt.toLocalDate();
Convert from java.util.Date
If you have a java.util.Date
object, convert to an Instant
. This class represents a moment on the timeline in UTC.
Instant instant = myUtilDate.toInstant();
Apply a time zone to get a ZonedDateTime
. Then obtain a LocalDate
as we saw above.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
LocalDate localDate = zdt.toLocalDate();
Immutable objects
The java.time classes follow the Immutable Objects design. Rather than alter (“mutate”) the value or attributes of a java.time object, a new java.time object is instantiated based on the attributes of the original object.
Generate String
When you want to generate a String to represent the LocalDate
value, define a formatting pattern.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/M/yy" );
String output = localDate.format( formatter );
By the way, I strongly advise against the use of two-digit years. The ambiguity raised and issues involved with parsing are not worth the savings of two characters.