Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should date properties be defined in a java class?

Tags:

java

date

I have a simple java object with several date properties and I always seem to change my mind on how to define them. Should the properties be defined as date objects or strings? The object is going to be used in struts 1.3 application with iBatis as the persistence layer and mysql as the database. The database columns are defined as datetime and they can possibly be null and I usually don’t care about the time portion.

public Date getForcastDate();

or

public String getForcastDate();

Most of the existing code base uses strings, but that just doesn’t seem quite right to me.

like image 647
xecaps12 Avatar asked Dec 06 '25 13:12

xecaps12


2 Answers

Keep your dates as Dates. That way you can change formatting depending on locales, check for invalid dates, sort by them etc.

By keeping them as strings you're potentially throwing away data (e.g. milliseconds if your formatter doesn't use them) and definitely behaviour.

Using strong-typing (e.g. keeping them as Dates) will aid in terms of development. Your method signatures become clearer, refactoring using IDE tooling becomes easier etc. Otherwise you end up with APIs that talk in nothing but strings, it's trivial to mix up parameters, and it becomes impossible to work out what's going on.

Tip: Check out Joda-Time as a better alternative to the standard java.util.Date.

like image 156
Brian Agnew Avatar answered Dec 08 '25 01:12

Brian Agnew


I would use Date object because it cleaner to store a Date and convert it to a String when needed. Otherwise you have to hard code a formatted date into a String field.

like image 43
jzd Avatar answered Dec 08 '25 03:12

jzd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!