用 Java 创建日期的正确方法是什么?

我对 Date 类的 JavaAPI 感到困惑。似乎所有内容都已经过时,并且链接到 Calendar 类。所以我开始使用 Calendar 对象来做我想要对 Date 做的事情,但是直觉上使用 Calendar 对象有点困扰我,因为我真正想做的只是创建和比较两个日期。

- 有没有简单的方法?-现在有了

Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.set(year, month, day, hour, minute, second);
Date date = cal.getTime(); // get back a Date object
221382 次浏览

You can try joda-time.

The excellent joda-time library is almost always a better choice than Java's Date or Calendar classes. Here's a few examples:

DateTime aDate = new DateTime(year, month, day, hour, minute, second);
DateTime anotherDate = new DateTime(anotherYear, anotherMonth, anotherDay, ...);
if (aDate.isAfter(anotherDate)) {...}
DateTime yearFromADate = aDate.plusYears(1);

You can use SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("21/12/2012");

But I don't know whether it should be considered more right than to use Calendar ...