Reputation: 36856
I'm working with Date objects in my code, and the documentation on many of the methods I'm using say that the method is deprecated and that I should use the Calendar object and its equivalent methods. The easiest example to remember is Date.getHours()
and Date.getMinutes()
methods say to use Calendar.get(Calendar.HOUR)
, etc.
But, in the case where I'm working with two dates, performing some math on them and then comparing them, they seem to be referring to the same instance on Calendar. The documentation for Calendar says to use Calendar.getInstance()
, but that seems to be returning a singleton Calendar instance.
The Date object was working just fine for me, but I'm afraid to use methods marked deprecated because that makes me feel like my code could break in a future version of the api.
Is it safe to use Date? Or is there a way to fetch unique Calendar instances?
Upvotes: 0
Views: 2560
Reputation: 4273
Calendar.getInstance() does not return a singleton. The following test
@Test
public void testCalendar() throws InterruptedException {
Calendar cal1 = Calendar.getInstance();
Thread.sleep(1000);
Calendar cal2 = Calendar.getInstance();
DateFormat df = new SimpleDateFormat("yyyyMMdd-hh:mm:ss.SSS");
String s1 = df.format(cal1.getTime());
String s2 = df.format(cal2.getTime());
assertEquals(s1, s2);
}
produces
org.junit.ComparisonFailure: expected:<20111129-02:50:4[5].507> but was:<20111129-02:50:4[6].507>
When doing date math, you should never work on the underlying milliseconds, because then you make the assumption that every day has 24 hours and every hour has 3600 seconds. Use the Calendar methods instead, or switch to JodaTime.
Upvotes: 2
Reputation: 4324
Create a Date object and then use Calendar.setDate(Date d) to define another Calendar object. Then you can easily manipulate the two dates.
Another way of manipulating the dates would be to manipulate their long values (in millis). You can subtract, add or whatever. After that you can create a Date object from the resulting long value, and then a Calendar from the Date.
Alternatively, you can use the Joda Time APIs which are relatively easy to use.
Regards!
Upvotes: 2