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

99封情书 提交于 2019-12-23 07:15:18

问题


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.


回答1:


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(); }



回答2:


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.




回答3:


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.




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/6267228/good-reason-to-use-java-util-date-in-an-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!