javajava.util.date

Alternatives for java.util.Date


Currently I am using the deprecated set Methods of java.util.Date. As I want to migrate away from it, what are the alternatives and what advantages do they have?

I need to have a Date that is set to today, midnight for a HQL query that selects everything that happened today.

Currently I use:

Date startingDate = new Date();
startingDate.setHours(0);
startingDate.setMinutes(0);
startingDate.setSeconds(0);

Solution

  • NOTE

    This answer is most likely no longer accurate for Java 8 and beyond, because there is a better date/calendar API now.


    The standard alternate is using the Calendar Object.

    Calendar cal = Calendar.getInstance(); // that is NOW for the timezone configured on the computer.
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    Date date = cal.getTime();
    

    Calendar has the advantage to come without additional libraries and is widely understood. It is also the documented alternative from the Javadoc of Date

    The documentation of Calendar can be found here: Javadoc

    Calendar has one dangerous point (for the unwary) and that is the after / before methods. They take an Object but will only handle Calendar Objects correctly. Be sure to read the Javadoc for these methods closely before using them.

    You can transform Calendar Objects in quite some way like:

    Have a read of the class description in the Javadoc to get the full picture.