I come from the C# world, so not too experienced with Java yet. Was just told by Eclipse that the 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?
Please note that
Calendar.getTime()
is nondeterministic in the sense that the day time part defaults to the current time.To reproduce, try running following code a couple of times:
Output eg.:
Running the exact same code a couple of minutes later yields:
So, while
set()
forces corresponding fields to correct values, it leaks system time for the other fields. (Tested above with Sun jdk6 & jdk7)Similar to what binnyb suggested, you might consider using the newer Calendar > GregorianCalendar method. See these more recent docs:
http://download.oracle.com/javase/6/docs/api/java/util/GregorianCalendar.html
(the pre-Java-8 way)
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. TheCalendar
class should be used instead:Take a look at the date Javadoc:
http://download.oracle.com/javase/6/docs/api/java/util/Date.html
I came across this question as a duplicate of a newer question which asked what the non-deprecated way to get a
Date
at a specific year, month, and day was.The answers here so far say to use the
Calendar
class, and that was true until Java 8 came out. But as of Java 8, the standard way to do this is:And then if you really really need a
java.util.Date
, you can use the suggestions in this question.For more info, check out the API or the tutorials for Java 8.
Date
itself is not deprecated. It's just a lot of its methods are. See here for details.Use
java.util.Calendar
instead.