关于Joda的DateTime的一个澄清点

Jam*_*sev 4 java jodatime

我想做点什么

private DateTime[] importantDates = {
        new DateTime(2013, 6, 15, 0, 0),
        new DateTime(2013, 9, 15, 0, 0)
};
Run Code Online (Sandbox Code Playgroud)

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

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

就此而言,我真的很喜欢它

private DateTime[] importantDates = {
        new DateTime(current_year, 6, 15),
        new DateTime(current_year, 9, 15),
};
Run Code Online (Sandbox Code Playgroud)

可以这样做吗?

Jon*_*eet 5

那么最简单的方法是:

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

这对于实例变量来说并不理想,因为它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),
    };
}
Run Code Online (Sandbox Code Playgroud)

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

  • @assylias:它无缘无故地引入了一个额外的实例变量.它确实有效,但它不会在C#中实例变量初始化器不能引用`this` ...将编辑. (2认同)