Java非ISO8601美国日历周转日期实现问题求助
美国周日起始周的日期解析问题
我需要将格式为YYYY0ww的字符串转换为基于美国日历的日期(每周最少1天,周日为一周首日),示例格式如2020051、2020052等,解析出的日期需为对应周的周日。
当前使用java.time包构建的格式化器代码如下:
DateTimeFormatter weekFormat = new DateTimeFormatterBuilder() .parseDefaulting(ChronoField.DAY_OF_WEEK, WeekFields.SUNDAY_START.getFirstDayOfWeek().getValue()) .appendValue(WeekFields.SUNDAY_START.weekBasedYear(), 4) .appendValue(WeekFields.SUNDAY_START.weekOfWeekBasedYear(), 3).parseStrict().toFormatter(); DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyyMMdd").withLocale(Locale.US);
测试用例执行出现异常:
TestCase.assertEquals("20201213", LocalDate.parse("2020051", weekFormat).format(dateFormat)); // 成功 TestCase.assertEquals("20201220", LocalDate.parse("2020052", weekFormat).format(dateFormat)); // 成功 TestCase.assertEquals("20201227", LocalDate.parse("2020053", weekFormat).format(dateFormat)); // 失败,解析日期为2020-12-20(对应2020年第52周) TestCase.assertEquals("20210103", LocalDate.parse("2021001", weekFormat).format(dateFormat)); // 成功
按部分日历网站信息,2020年美国日历存在第53周,2020053应对应2020-12-27,但解析失败。
尝试为周格式化器设置.withResolverStyle(ResolverStyle.LENIENT)后,2020053解析成功,但2021001测试失败:
TestCase.assertEquals("20210103", LocalDate.parse("2021001", weekFormat).format(dateFormat)); // 失败,解析日期为2020-12-27(对应2020年第53周)
我困惑于非ISO8601日历的周转日期为何难以实现,该场景并不特殊,希望得到问题原因的反馈。
更新:经思考,我可能误信部分网站信息,美国日历规则是包含1月1日的周日起始周为当年第一周,因此可能不存在第53周。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

