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

seb*_*seb 85 java datetime calendar date

我对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
Run Code Online (Sandbox Code Playgroud)

Max*_*axx 104

您可以使用SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("21/12/2012");
Run Code Online (Sandbox Code Playgroud)

但我不知道是否应该考虑使用Calendar 更正确 ...

  • 是的,你可能是对的,但它也是最"可读"的约会方式,所以如果你不是在循环中做的话...... (5认同)
  • 请记住,SimpleDateFormat不是同步的.如果重用实例并且两个方法访问相同的SimpleDateFormat,则会导致错误. (3认同)

Chr*_*ght 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);
Run Code Online (Sandbox Code Playgroud)


Ser*_*huk 15

你可以尝试joda-time.