Search code examples
javadatejava.util.date

Good Reason to use java.util.Date in an API


Are there any specific reasons to use a Date class in an API (for example, in an employee birth date field) rather that a long or Long.

There is some discussion of this in: java-date-vs-calendar, but I would like to know specifically if there is any justification for using Dates, when a long (or Long) seems so much simpler.

Of course I would use TimeZone and SimpleDateFormatter to parse and display dates in a GUI, and maybe Calendar to perform manipulations, but I am concerned only about the storage and representation of date in the data model/API in this question.

Update: An example of one reason why I would not choose Date is that it is mutable. So if I expose a Date in my API, callers can call setTime(long) and this seems to be a violation of basic encapsulation. To me this seems to outweigh the benefit of the added clarity that using a Date provides, since I could just call the long property timeInMillisecondsSinceEpoch and communicate the same information to callers.


Solution

  • The Date class is part of the API and as such a valid option if it fits your purpose. There are many deprecated methods in it that were replaced by the Calendar class, so make sure you avoid using those methods.

    The answer will depend on what is what you need to accomplish. If you just need to sort by the date, a long will be more than enough. A Date value would add some readability to it, but not more functionality. Using Date will not be detrimental either, so the readability factor should be considered.

    If the field will be private, you can actually store it as a long and have a getter and a setter that use Date :

    private long mDOB;
    
    public Date getDOB () { return new Date(mDOB);}
    public void setDOB (Date dob) { mDOB = dob.getTime(); }