我的 bean 中有一个字符串日期 yyyymm,想与当前月份或上一个日历日期进行比较

I have a string date yyyymm in my bean and want to compare with present month or previous Calendar Date

我有一个 java bean String month,它有一个 "YYYYMM" 值。

我想使用日历日期将该值与当前月份或上个月进行比较。我不知道该怎么做。

目前,在 DateBean bean class 中,我正在使用下面的 属性,例如:

private String month;

List<DateBean> 这给了我 "YYYYMM" 格式值,例如 201906.

我想将它与当前日历日期进行比较,以检查月份是否为当前月份。

我该怎么做?

您会在 bean 中的 字符串 中保留一个整数值吗? floating-point 值?你当然不会。那为什么是一个月的价值呢?当然你也不会那样做。你想要:

private YearMonth month;

YearMonth class 是 java.time 的一部分,现代 Java 日期和时间 API。当您的程序接受日期和时间数据作为字符串时,将其解析为适当的 date-time 类型。你可能会发现有一个构造函数很方便,例如:

private static final DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("uuuuMM");

public DateBean(String month) {
    this.month = YearMonth.parse(month, monthFormatter);
}

比较简单的使用YearMonthequals方法,例如:

    List<DateBean> dateBeans
            = List.of(new DateBean("201901"), new DateBean("201906"));
    YearMonth currentMonth = YearMonth.now(ZoneId.of("Europe/Sofia"));
    for (DateBean bean : dateBeans) {
        if (bean.getMonth().equals(currentMonth)) {
            System.out.println("" + bean.getMonth() + " is current month");
        } else {
            System.out.println("" + bean.getMonth() + " is not current month");
        }
    }

输出为:

2019-01 is not current month
2019-06 is current month

由于所有时区的新月并非在同一时间开始,我建议您将所需的时区传递给 YearMonth.now()

编辑: Basil Bourque 在他的评论中可能有一个很好的观点:如果你的 DateBean class 的唯一目的是结束你的一年并且月字符串,你可能更好 replacing it with YearMonth completely than wrapping a YearMonth.

Link: Oracle tutorial: Date Time 解释如何使用 java.time.