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.
The java. util. Date class represents a particular moment in time, with millisecond precision since the 1st of January 1970 00:00:00 GMT (the epoch time). The class is used to keep coordinated universal time (UTC).
Immutability and Thread-Safety. Another advantage is that all time representations in Java 8 Date Time API are immutable and thus thread-safe. All mutating methods return a new copy instead of modifying state of the original object. Old classes such as java.
sql. Date just represent DATE without time information while java. util. Date represents both Date and Time information.
The DateFormat class in Java is used for formatting dates. A specified date can be formatted into the Data/Time string. For example, a date can be formatted into: mm/dd/yyyy.
If you use an integer to represent a Date in your API you will be adding an extra, unnecessary layer of complexity that will need extra documentation and make your API harder to use.
By using an integer you have to let the client know what the base date is, what you're measuring (e.g. seconds, milliseconds, minutes etc?) and force the client to do the conversion. Keeping a Date object in your API makes it simpler and friendlier IMO. And unless, for whatever reason, there are very serious performance implications I would suggest keeping the Date in your API, even if you need to do more coding internally. That's one of the things that makes a good API a good API... Not making your client jump through hoops.
Personally, as bad as the date and time API in Java is, I tend to use Date
. It just has more semantic value. Additionally, you don't have to guess whether it's seconds or milliseconds.
A date is not a number, it is a point in time. The fact that you can represent that with a number is an implementation detail that should be hidden.
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(); }
long
A long
or Long
exposes internal implementation details that could change. Some utilities and libraries track date-time by seconds, microseconds, or nanoseconds rather than the milliseconds you might assume.
The count is from an epoch reference date-time. There are dozens of such epochs in use by various software systems. So which epoch can be ambiguous.
Working with date-time values as a number from epoch is inherently confusing as they are not human readable. So debugging and testing are complicated.
Why not track text as a series of octets or even bits? Because we want libraries to handle the nitty-gritty complexities and chores (UTF-8, MacRoman, searching, replacing, trimming, etc.) for us. Likewise, date-time values should be handled as date-time data types.
If given a count of seconds or milliseconds since epoch of first moment of 1970 in UTC, 1970-01-01T00:00Z, parse into Instant
using convenient factory methods found on that class.
Date
or Calendar
That said, the java.util.Date and .Calendar classes are terrible. Avoid them whenever possible.
With Java 8 and later, we have the modern java.time package. These supplanted the terrible old legacy classes as of the adoption of JSR 310.
For Java 6 & 7, see the bullets below for ThreeTen-Backport project, and ThreeTen-ABP for earlier Android.
When storing or exchanging date-time values as text, use Strings in the standard ISO 8601 format. These are unambiguous, easy to read by humans across cultures, and easy to parse by machine.
I would not choose Date is that it is mutable.
Using immutable objects makes sense for date-time values. The java.time classes use immutable objects as part of the strategy to be inherently thread-safe.
to parse and display dates in a GUI
Keep separate the tracking of moments, which is usually best done using Instant
, from generating text for presentation to users. For presentation, adjust into a time zone (ZoneId
) to get a ZonedDateTime
, from which you can generate text using a DateTimeFormatter
.
I am concerned only about the storage and representation of date in the data model/API
For storage, adjust to UTC by working with Instant
class. Generate ISO 8601 strings by default using toString
method. For representation in your data model, use Instant
for a UTC value unless you have a specific need per your business rules to consider a specific time zone, in which case use ZonedDateTime
.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With