Java: Why is the Date constructor deprecated, and

2019-01-03 12:51发布

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?

11条回答
甜甜的少女心
2楼-- · 2019-01-03 13:11

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:

Calendar c = Calendar.getInstance();
c.set(2010, 2, 7); // NB: 2 means March, not February!
System.err.println(c.getTime());

Output eg.:

Sun Mar 07 10:46:21 CET 2010

Running the exact same code a couple of minutes later yields:

Sun Mar 07 10:57:51 CET 2010

So, while set() forces corresponding fields to correct values, it leaks system time for the other fields. (Tested above with Sun jdk6 & jdk7)

查看更多
在下西门庆
3楼-- · 2019-01-03 13:13

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

查看更多
太酷不给撩
4楼-- · 2019-01-03 13:13
new GregorianCalendar(1985, Calendar.JANUARY, 1).getTime();

(the pre-Java-8 way)

查看更多
We Are One
5楼-- · 2019-01-03 13:15

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

查看更多
仙女界的扛把子
6楼-- · 2019-01-03 13:18

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:

LocalDate localDate = LocalDate.of(1985, 1, 1);

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.

查看更多
Deceive 欺骗
7楼-- · 2019-01-03 13:21

Date itself is not deprecated. It's just a lot of its methods are. See here for details.

Use java.util.Calendar instead.

查看更多
登录 后发表回答