1

First, please note that this question is not a duplicate of this Question: Java Date vs Calendar. My question is much more specific. The referenced question asks "what" (or "which"), but I already know the "what" and am asking the "why".

I am on a team working on enhancements to an existing Java project for a client. This Java project uses java 6, and does not have Joda Time as a dependency. After inquiring, it looks like adding Joda Time or upgrading to Java 8 are not options.

So, when it comes to representing date/time as a field in an object, we have to use either Calendar or Date for property typing. The legacy code of this project is littered with Objects that use Calendar to represent date/time fields -- fields that we would never have cause to manipulate (as in add or subtract units of time, etc). I know that this is bad practice, as Calendar is a more complex object, while Date is simpler and would work just as well. (And granted, I know that both are fundamentally wrappers for a long of epoch millis, are mutable, and are poorly designed, but again these are our only two options.)

In other words, an object like this:

public class Reservation {

    private Guest guest;
    // Set only once, never used for calculations
    private Calendar dateReserved;
    ...
}

Should be this instead:

public class Reservation {

    private Guest guest;
    // Set only once, never used for calculations
    private Date dateReserved;
    ...
}

I then noticed that when adding new Objects for new features, my team was following the same convention of using Calendar instead of Date. When I brought this up, the reply was that it's better to use Calendar because it can do more and doesn't have all these deprecated methods like Date does.

I know that this reasoning is oversimplified. I also see that this answer to the broader question of usage expresses the same view, namely that Calendar should not be used for property typing. However, the answer doesn't contain much explanation as to why Calendar should not be preferred.

So I already know the "What". But I'm trying to make the case to my team, so my question is, "Why"? Why, when property typing, should Date be preferred to Calendar? What are the disadvantages of using Calendar instead of Date for property typing?

Community
  • 1
  • 1
James Dunn
  • 8,064
  • 13
  • 53
  • 87
  • 3
    "I know that both are fundamentally the same concept" - um, no they're not. A `Date` is a point in time, with no associated calendar system or time zone. A `Calendar` has a calendar system in terms of which concrete class it is (e.g. GregorianCalendar) and can be set to any time zone. Which time zone are you interested in, and how do you expect to explain that to `Date`? – Jon Skeet Mar 18 '15 at 15:45
  • @JonSkeet You're right, I should clarify -- what I meant is that I know they both do what they do by wrapping a long of epoch milliseconds. I'll change my wording, it was poor. As for time zones... hmmm. That could become an issue... are you saying Calendar would be preferable if Reservations happened in different time zones? – James Dunn Mar 18 '15 at 15:56
  • Well they both wrap a number of milliseconds since the Unix epoch - but Calendar *also* has a time zone field. It's hard to know what you need seeing as we don't know what you do with the field... – Jon Skeet Mar 18 '15 at 15:57

3 Answers3

1

I agree with Jon Skeet's comment regarding calendar systems and time zones, and I think your premise is fundamentally flawed. Dates aren't better than Calendars. If you're never ever ever going to compare times, or never ever ever have two dates in different time zones, then sure, the smaller footprint can be nice, I guess, but at that point, just use longs and Unix timestamps. Calendars are by far the better object model, and after all, if you absolutely need it, you can get a Date object from it.

Josh Ghiloni
  • 1,260
  • 8
  • 19
1

If you are stuck having to choose between Date and Calendar when property typing: Use Calendar if either one of these is true:

  • You need to be able to adjust the date/time after it is initially set (such as changing the month while leaving the day and hour the same).

  • You need to be aware of timezone.

Otherwise, use Date for the following reasons:

  1. Expressing your intentions accurately. If you use Calendar, you are implying that you want a certain functionality that you don't actually intend to use (timezones, changing the day or month, etc).
  2. Less hassle with String representations. For example, consider this class:

    public class Reservation {
        private Guest guest;
        private Calendar dateReserved;
    
        @Override
        public String toString() {
            return String.format("Reservation{guest=%s,dateReserved=\"%s\"}",
                    guest, dateReserved);
        }
    }
    

    Now if you print out an instance of this class, you'll get something hideous:

    Reservation{guest=Guest{id=17,name="John Smith"},dateReserved="java.util.GregorianCalendar[time=1426707020619,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2015,MONTH=2,WEEK_OF_YEAR=12,WEEK_OF_MONTH=3,DAY_OF_MONTH=18,DAY_OF_YEAR=77,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=0,HOUR_OF_DAY=12,MINUTE=30,SECOND=20,MILLISECOND=619,ZONE_OFFSET=-28800000,DST_OFFSET=3600000]"}

    Whereas if you had used Date instead, you'd get this:

    Reservation{guest=Guest{id=17,name="John Smith"},dateReserved="Wed Mar 18 12:34:26 PDT 2015"}

    So if you use Calendar and you want your toString() to be usable, you would need to call dateReserved.getTime() -- which means you'd need to add a null check. This goes for whether or not you end up using a DateFormat object.

  3. Date is a smaller object, quicker to instantiate and with less overhead.

  4. Date is practically immutable -- meaning that the only way to change a date object is to use deprecated methods. So, as said in point 1, expressing your intentions matters. If your date field should be immutable, don't confuse developers who will touch your code in the future by using Calendar (unless of course you need timezone awareness).

  5. "Date" is a more intuitive name than "Calendar" for the type of a field that represents a single point in time.

James Dunn
  • 8,064
  • 13
  • 53
  • 87
0

Date object has fewer fields and occupies less memory than Calendar object and is also faster to instantiate.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275