Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives for java.util.Date [closed]

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);
like image 500
Sangram Anand Avatar asked Sep 23 '13 11:09

Sangram Anand


People also ask

Is Java Util calendar deprecated?

util. Date are deprecated since Java 1.1, the class itself (and java. util. Calendar , too) are not officially deprecated, just declared as de facto legacy.

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

Is SimpleDateFormat deprecated?

Class SimpleDateFormat. Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.

Is date class deprecated in Java?

Date Class. Many of the methods in java. util. Date have been deprecated in favor of other APIs that better support internationalization.


2 Answers

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.

like image 175
Angelo Fuchs Avatar answered Sep 26 '22 11:09

Angelo Fuchs


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();
like image 31
Jean Logeart Avatar answered Sep 25 '22 11:09

Jean Logeart