分配中使用的静态块设置日历 - 日期

Static block setting Calendar for usage in assignment - dates

我目前有以下代码,它不能正常工作,因为我怀疑我的 static block 在我分配 programCutoffDate2015 之前没有被调用。

private final static Calendar programCutoffDate2015Cal = Calendar.getInstance();
    static{
        programCutoffDate2015Cal.set(2015, 12,31);
    }
    private final static Date programCutoffDate2015 = programCutoffDate2015Cal.getTime();

之前我使用的是已弃用的 API:

private final static Date programCutoffDate2015 = new Date(2015, 12,31);

我应该如何使用 JDK 中未弃用的较新 API 来实现相同的结果?

Date没有时区概念,是可变的。在过去十年左右的时间里,它被普遍认为是一个贫穷的 API。我建议使用 JSR 310 API,添加到 Java 8,但 backports 可以使用旧版本。

LocalDate date = LocalDate.of(2015,12,31);

注意:虽然这是基于 JodaTime 的出色工作,但它是一个不同的 API。

Is there any way to have that static block executed before the declaration of programCutoffDate2015 or another way?

静态块按照它们在代码中出现的顺序执行,从上到下。即使多个线程试图同时加载 class,也没有办法改变它。

假设您有另一个 API 存在上述问题,我建议使用辅助方法包装它。

private static Date newDate(int year, int month, int day) {
    Calendar cal = Calendar.getInstance();
    cal.set(year, month, day);
    // if you want the last milli-second of the day for an upper bound
    cal.add(Calendar.DAY_OF_MONTH, 1);
    cal.add(Calendar.MILLISECOND, -1);
    return cal.getTime();
}

private final static Date programCutoffDate2015 = newDate(2015, 12, 31);

甚至更好

private static LcoalDate lastDayOf(int year) {
    return LocalDate.of(year+1, 1, 1).minusDays(1);
}

DateLocalDate 之间的一个显着区别是日期包含时间,尽管这可能不是故意的,因为 2015/12/31 12:00 会在您的 Date 对象之后还在 2015 年。LocalDate 只是一个日期,如果你也想要一个时间,你可以使用 LocalDateTime