The parameterized constructors of the java.util.Date class are deprecated. What is the alternative?

Note: this answer was written in 2009. Since then, java.time has become the preferred date/time API in Java.


Ideally, use Joda Time instead. It's an infinitely superior API to the built-in one. You'd then want to choose between LocalDateTime and DateTime depending on your exact requirements (it's a complicated area - I'm not going to try to summarise in a sentence or two, but the docs do a good job).

If absolutely necessary, use a java.util.Calendar and convert that to a Date when you need to.


Calendar !

Calendar cal = Calendar.getInstance();
cal.set(2009, Calendar.DECEMBER, 12);

Notice that i didn't put 12 for december because it's actually 11 (january is 0).

Then, you can add or remove seconds, minutes, hours, days, months or year easily with :

cal.add(Calendar.HOUR, 2);
cal.add(Calendar.MONTH, -5);

And finally, if you want a Date :

cal.getTime();

If you look at the Javadoc it points you towards using Calendar.

As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min) or GregorianCalendar(year + 1900, month, date, hrs, min).

If you look at the Date constructor params you'll see why it was deprecated:

Parameters:

year - the year minus 1900.
month - the month between 0-11.
date - the day of the month between 1-31.
hrs - the hours between 0-23.
min - the minutes between 0-59.

year isn't what you expect and neither is month.

To represent the date you have mentioned you need to call Date like this (not recommended)

new Date(2009-1900, 12-1, 9)

The alternative using Calendar is

Calendar cal = Calendar.getInstance();
cal.set(2009, 11, 9); //year is as expected, month is zero based, date is as expected
Date dt = cal.getTime();