Joda-Time new DateTime() 与 DateTime.now()

Joda-Time new DateTime() vs DateTime.now()

从 Joda-Time 时间版本 2.0 开始,引入了静态方法 org.joda.time.DateTime#now()。 对我来说,不清楚使用 new DateTime() 有什么好处(因为代码只是委托)。

public static DateTime now() {
    return new DateTime();
}

同样来自 java 文档,我不清楚我应该更喜欢哪一个。

new DateTime

Obtains a {@code DateTime} set to the current system millisecond time using ISOChronology in the default time zone.

DateTime#now()

Constructs an instance set to the current system millisecond time using ISOChronology in the default time zone.

有人可以解释在哪种用例中应该首选哪个吗?

new DateTime() 要求分配一个新对象。 DateTime.now 可以跨请求重用单个对象,因为 DateTime 实例是不可变的。这可能会减少内存流失。

但在很大程度上我怀疑你使用哪个很重要。

我认为没有任何区别。在您的代码中使用 DateTime.now() 看起来比 new DateTime() 更优雅。这是 DateTime.now() 源代码。

public static DateTime now() {
    return new DateTime();
}

添加了now()方法,使Joda-Time更接近Java8中的java.time.*,使转换过程更容易一些。这两种方法具有完全相同的行为。