Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Best Practice for manipulating and storing dates in Java? [duplicate]

Tags:

java

date

What is the best practice for manipulating and storing Dates e.g. using GregorianCalendar in an enterprise java application?

Looking for feedback and I will consolidate any great answers into a best practice that others can use.

like image 707
BestPractices Avatar asked Jan 30 '10 15:01

BestPractices


People also ask

Can date be stored as string in Java?

We can convert Date to String in java using format() method of java. text. DateFormat class.


2 Answers

The best practice is usually precisely NOT to think in term of heavy date objects but to store a point in time. This is typically done by storing a value that doesn't suffer from corner cases nor from potential parsing problems. To do this, people usually store the number of milliseconds (or seconds) elapsed since a fixed point that we call the epoch (1970-01-01). This is very common and any Java API will always allow you to convert any kind of date to/from the time expressed in ms since the epoch.

That's for storage. You can also store, for example, the user's preferred timezone, if there's such a need.

Now such a date in milliseconds, like:

System.out.println( System.currentTimeMillis() ); 1264875453 

ain't very useful when it's displayed to the end user, that's for granted.

Which is why you use, for example, the example Joda time to convert it to some user-friendly format before displaying it to the end-user.

You asked for best practice, here's my take on it: storing "date" objects in a DB instead of the time in milliseconds is right there with using floating point numbers to represent monetary amounts.

It's usually a huge code smell.

So Joda time in Java is the way to manipulate date, yes. But is Joda the way to go to store dates? CERTAINLY NOT.

like image 183
SyntaxT3rr0r Avatar answered Oct 02 '22 14:10

SyntaxT3rr0r


Joda is the way to go. Why ?

  1. it has a much more powerful and intuitive interface than the standard Date/Time API
  2. there are no threading issues with date/time formatting. java.text.SimpleDateFormat is not thread-safe (not a lot of people know this!)

At some stage the Java Date/Time API is going to be superseded (by JSR-310). I believe this is going to be based upon the work done by those behind Joda, and as such you'll be learning an API that will influence a new standard Java API.

like image 33
Brian Agnew Avatar answered Oct 02 '22 12:10

Brian Agnew