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

时间:2011-06-22 08:51:47

标签: java datetime date calendar

我对Date类的Java API感到困惑。所有内容似乎都已弃用,并且链接到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

3 个答案:

答案 0 :(得分:104)

您可以使用SimpleDateFormat

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

但我不知道是否应该考虑更多正确而不是使用日历......

答案 1 :(得分:35)

优秀的joda-time库几乎总是比Java的Date或Calendar类更好的选择。以下是一些例子:

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);

答案 2 :(得分:15)

您可以尝试joda-time

相关问题