Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 917
James Scriven Avatar asked Jun 07 '11 15:06

James Scriven


People also ask

What does Java Util date do?

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).

What is the advantage of using date time API in Java 8?

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.

Should I use Java Util date or Java sql date?

sql. Date just represent DATE without time information while java. util. Date represents both Date and Time information.

What should I use for date in Java?

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.


5 Answers

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.

like image 52
Paul Sasik Avatar answered Nov 11 '22 18:11

Paul Sasik


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.

like image 36
musiKk Avatar answered Nov 11 '22 18:11

musiKk


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.

like image 34
gpeche Avatar answered Nov 11 '22 19:11

gpeche


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(); }
like image 43
Aleadam Avatar answered Nov 11 '22 19:11

Aleadam


Never use a 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.

Never use Date or Calendar

That said, the java.util.Date and .Calendar classes are terrible. Avoid them whenever possible.

Always use java.time

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.

Always use ISO 8601 strings

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.

Immutable objects

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.

Presentation

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.


About java.time

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?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

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.

like image 1
Basil Bourque Avatar answered Nov 11 '22 19:11

Basil Bourque