【问题标题】:Use DateTimeFormatterBuilder for parsing dates of missing day and default to end of month使用 DateTimeFormatterBuilder 解析缺失日期的日期,默认为月末
【发布时间】:2019-10-31 03:20:24
【问题描述】:

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

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()) 手动调整它。

【问题讨论】:

    标签: java localdate


    【解决方案1】:
    DateTimeFormatter f = new DateTimeFormatterBuilder()
          .appendPattern("MM.yyyy")
          .parseDefaulting(DAY_OF_MONTH, 31) // set 31
          .toFormatter();
    

    只需设置DAY_OF_MONTH31DAY_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

    【讨论】:

      猜你喜欢
      • 2019-09-19
      • 2016-01-30
      • 1970-01-01
      • 2018-11-28
      • 2021-12-06
      • 2020-02-08
      • 2012-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多