I\'m trying to make a deep copy of an object, including a GregorianCalendar
instance. I\'m always wary of using clone()
and it doesn\'t seem to hav
Use the modern java.time classes that supplanted GregorianCalendar
.
GregorianCalendar.from( // Convert from modern object to legacy class object.
myGregorianCalendar.toZonedDateTime() // Convert from legacy to modern.
) // Returns a new `GregorianCalendar` object.
But better to stop using GregorianCalendar
altogether, and just use ZonedDateTime
.
ZonedDateTime
The terrible GregorianCalendar
class was years ago supplanted by the java.time classes defined in JSR 310. Specifically replaced by the ZonedDateTime class.
You can convert back and forth using new to…
/from…
methods added to the old classes.
ZonedDateTime zdt = myGregorianCalendar.toZonedDateTime() ;
Going the other direction.
GregorianCalendar myGregorianCalendar = GregorianCalendar.from( zdt ) ;
To address your Question specifically, combine these two conversions to get another GregorianCalendar
object.
GregorianCalendar gc = GregorianCalendar.from( myGregorianCalendar.toZonedDateTime() ) ;
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.
java.util.Calendar
has overridden clone()
which is working, so use it. Furthermore, Calendar
doesn't have deep data hierarchy - its data are mainly int
s.
To extend the answer, you can call SerializationUtils.clone(..)
(from commons-lang) on any object which makes a deep copy, if the whole data hierarchy implements Serializable
Uh, clone()
sucks.
Is it that hard? You only have to set 3 things, I believe, the time, the time zone, and the locale. All those fields have getters and setters. Make a quite utility method to return a copy?
Specifically, the quickest line of code to copy a Calendar is:
GregorianCalendar newCalendar = (Calendar)(oldCalendar.clone());