gpt4 book ai didi

java - 使用 DateTimeFormatterBuilder 解析缺失日期的日期,默认为月底

转载 作者:行者123 更新时间:2023-11-30 01:49:20 24 4
gpt4 key购买 nike

我需要解析各种格式的日期。其中一些缺少“日”。现在我想默认到月底。我不确定是否有直接的方法可以默认为月底

DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendPattern("MM.yyyy")
.parseDefaulting(DAY_OF_MONTH, 1) // can we default to end of month?
.toFormatter();

LocalDate.parse("11.2017", f)

但如果不是,我怎么知道原始日期缺少这一天(或者使用了默认值),因此我需要使用 LocalDate.parse("11.2017", f) 手动调整它.with(TemporalAdjusters.lastDayOfMonth()).

最佳答案

DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendPattern("MM.yyyy")
.parseDefaulting(DAY_OF_MONTH, 31) // set 31
.toFormatter();

只需将DAY_OF_MONTH设置为31DAY_OF_MONTH将根据rangeUnit来选择最后一天解析月份

/**
* The day-of-month.
* <p>
* This represents the concept of the day within the month.
* In the default ISO calendar system, this has values from 1 to 31 in most months.
* April, June, September, November have days from 1 to 30, while February has days
* from 1 to 28, or 29 in a leap year.
* <p>
* Non-ISO calendar systems should implement this field using the most recognized
* day-of-month values for users of the calendar system.
* Normally, this is a count of days from 1 to the length of the month.
*/
DAY_OF_MONTH("DayOfMonth", DAYS, MONTHS, ValueRange.of(1, 28, 31), "day"),

示例:

LocalDate parse = LocalDate.parse("02.2017", f);
System.out.println(parse.getDayOfMonth());

输出:

28

关于java - 使用 DateTimeFormatterBuilder 解析缺失日期的日期,默认为月底,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56632866/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com