关于Joda的DateTime的一个澄清点

时间:2013-06-26 20:37:42

标签: java jodatime

我想做点什么

private DateTime[] importantDates = {
        new DateTime(2013, 6, 15, 0, 0),
        new DateTime(2013, 9, 15, 0, 0)
};

哪一年总是当年。 Joda是否允许这样的事情,没有计算?

示例:现在我们生活在2013年。我宁愿不对此值进行硬编码。

就此而言,我真正喜欢它

private DateTime[] importantDates = {
        new DateTime(current_year, 6, 15),
        new DateTime(current_year, 9, 15),
};

可以这样做吗?

2 个答案:

答案 0 :(得分:5)

最简单的方法是:

int year = new DateTime().getYear();
DateTime[] dates = new DateTime[] {
    new DateTime(year, 6, 15, 0, 0),
    new DateTime(year, 9, 15, 0, 0),
};

这对于实例变量并不理想,因为它没有充分的理由引入了额外的实例变量(year),但您可以轻松地将其放入辅助方法中:

private final DateTime[] importantDates = createImportantDatesThisYear();

private static DateTime[] createImportantDatesThisYear() {
    int year = new DateTime().getYear();
    return new DateTime[] {
        new DateTime(year, 6, 15, 0, 0),
        new DateTime(year, 9, 15, 0, 0),
    };
}

请注意,所有此代码都假定您需要

答案 1 :(得分:4)

DateTime.now().getYear()将返回当前年份(javadoc)。例如,您可能希望使用其中一个重载版本来调整时区。