Java: Why is the Date constructor deprecated, and what do I use instead?

Svish picture Svish · Apr 15, 2011 · Viewed 215k times · Source

I come from the C# world, so not too experienced with Java yet. I was just told by Eclipse that Date was deprecated:

Person p = new Person();
p.setDateOfBirth(new Date(1985, 1, 1));

Why? And what (especially in cases like above) should be used instead?

Answer

BuffaloBuffalo picture BuffaloBuffalo · Apr 15, 2011

The java.util.Date class isn't actually deprecated, just that constructor, along with a couple other constructors/methods are deprecated. It was deprecated because that sort of usage doesn't work well with internationalization. The Calendar class should be used instead:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1988);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date dateRepresentation = cal.getTime();

Take a look at the date Javadoc:

http://download.oracle.com/javase/6/docs/api/java/util/Date.html