Question

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);
Was it helpful?

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:

  • add a day (cal.add(Calendar.DAY_OF_YEAR, 1);)
  • "scroll" through the week (cal.roll(Calendar.DAY_OF_WEEK, 1);)
  • etc

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

OTHER TIPS

The best alternative is to use the Joda Time API:

Date date = new DateMidnight().toDate();     // today at 00:00

To avoid the to-be deprecated DateMidnight:

Date date = new DateTime().withMillisOfDay(0).toDate();

Date does not handle internationalization properly, that's why it was deprecated.

Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Unfortunately, the API for these functions was not amenable to internationalization. As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated.

The simplest alternative is to use java.util.Calendar instead:

Calendar calendar = Calendar.getInstance(); // get a calendar instance (current)

and the call calendar.set(...) methods.

You may use joda dates library , you will get lots of flexibility with that. Otherwise you can use java.util.Calendar for creating custom date.

1、The alternate is using the java.util.Calendar Object;

2、Detailed usage, please refer to the link below;

http://www.leepoint.net/notes-java/other/10time/30calendar.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top