tl;dr
newEmployee.setHiredDate( oldEmployee.getHiredDate() ) ; // No need to copy/clone an immutable `LocalDate` object.
- Use
java.time.Instant
instead of java.util.Date
.
- Use
java.time.LocalDate
for a date-only value.
- Being immutable, re-use the java.time object rather than copy/clone.
java.time
The Date
class is among the troublesome old date-time classes than are now legacy, supplanted by the java.time classes.
Instant
The modern equivalent to Date
is Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ; // Current moment in UTC.
You can convert using new methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
LocalDate
But you seem to be interested in a date-only value without a time-of-day and without a time zone. If so, use LocalDate
.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) ;
LocalDate ld = LocalDate.parse( "02-11-2017" , f ) ;
Immutable object can be reused rather than cloned/copied
The java.time classes use immutable objects. So no need to copy or clone. Simply assign the same object.
The new cloned Employee
object gets a reference to the same LocalDate
object held by the original Employee
object.
Strings
By the way, you can serialize the java.time objects to standard ISO 8601 formatted strings by calling toString
.
String x = ld.toString() ; // Serialize object’s value as text in standard ISO 8601 format.
Instantiate by calling parse
.
LocalDate ld = LocalDate.parse( "2017-02-11" ) ; // Parse text to instantiate object.
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?
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.