Store date attributes as primitive longs?

I was reading the item 24 of this book and, in one of the last paragraphs, the author comments about storing date objects as a primitive long. The text is about making defensive copies of objects in your constructors and accessor methods.

So instead of

public void setDate(Date date) { = date;


you should use

public void setDate(Date date) { = new Date(date.getTime());


This is pretty obvious after years developing O.O. software, and explaining it is out of the scope of this post. Now, about using primitive longs. It actually seems to be a very interesting idea. Since you would have to use the long value of the local (private) date all the time to create the defensive copies, storing it as a primitive long right away would get us more clean and readable code.

The constructor would simply store the long date, and the acessor would be as simple as

public Date getDate() {

    return new Date(myDateAsLong);


Also, it would be easier to store the date in the database, since we wouldn’t need to convert a Date object to a format the database understand.

Now, the bigger question: why didn’t I think about this before??

This entry was posted in java and tagged , , , . Bookmark the permalink.

4 Responses to Store date attributes as primitive longs?

  1. Fábio Serra says:

    Great post… Is incredible how a problem can be resolved through of so simple ways. 😀

  2. Paulo Renato says:

    Yep! The only problem I see with this solution for now is that you wouldn’t be using database timestamps for date. But I’m not sure this is that bad at all…

  3. gwebtools says:

    How will you query the database finding between date ranges, when you use the long type?

    • This is a good question. This kind of solution always have to take into account several things, like the usage pattern. Perhaps, if you are going to do date range querying, it is not such a good idea, but this query wouldn’t actually be that complicated. The long value is an always growing number, which means you can convert both sides of the range and use those in the query.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s