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

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

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

目前,在DateBeanbean 类中,我使用如下属性:

private String month;

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

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

我怎样才能做到这一点?


手掌心
浏览 83回答 1
1回答

HUH函数

您会在 bean 的字符串中保留一个整数值吗?浮点值?你当然不会。那为什么是一个月的价值呢?你当然也不会那样做。你要:private YearMonth month;该类YearMonth是现代 Java 日期和时间 API java.time 的一部分。当您的程序接受日期和时间数据作为字符串时,将其解析为适当的日期时间类型。你可能会发现有一个构造函数很方便,例如:private static final DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("uuuuMM");public DateBean(String month) {&nbsp; &nbsp; this.month = YearMonth.parse(month, monthFormatter);}比较简单的使用equals的方法YearMonth,例如:&nbsp; &nbsp; List<DateBean> dateBeans&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; = List.of(new DateBean("201901"), new DateBean("201906"));&nbsp; &nbsp; YearMonth currentMonth = YearMonth.now(ZoneId.of("Europe/Sofia"));&nbsp; &nbsp; for (DateBean bean : dateBeans) {&nbsp; &nbsp; &nbsp; &nbsp; if (bean.getMonth().equals(currentMonth)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("" + bean.getMonth() + " is current month");&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("" + bean.getMonth() + " is not current month");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }输出是:2019-01 is not current month2019-06 is current month由于新月份并非在所有时区的同一时间点开始,我建议您将所需的时区传递给YearMonth.now()。编辑: Basil Bourque 在他的评论中可能有一个很好的观点:如果你的课程的唯一目的DateBean是包装你的年份和月份字符串,你可能最好用完全替换它而不是包装一个.YearMonthYearMonth链接: Oracle 教程:解释如何使用 java.time 的日期时间。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java