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);
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.
DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.
Class SimpleDateFormat. Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.
Date Class. Many of the methods in java. util. Date have been deprecated in favor of other APIs that better support internationalization.
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:
cal.add(Calendar.DAY_OF_YEAR, 1);
)cal.roll(Calendar.DAY_OF_WEEK, 1);
)Have a read of the class description in the Javadoc to get the full picture.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With