【问题标题】:Parse a String with week and year into a LocalDate [duplicate]将带有星期和年份的字符串解析为 LocalDate [重复]
【发布时间】:2019-08-29 14:58:00
【问题描述】:

我要解析的字符串类型:“36/2017”,一年中的第 36 周,一年中的 2017 年。

我的代码:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                    .appendPattern("w/uuuu")
                    .parseDefaulting(ChronoField.DAY_OF_WEEK, 1)
                    .toFormatter();
LocalDate date = LocalDate.parse("36/2017", formatter);

我添加了默认日期。

我有这条消息:

java.time.format.DateTimeParseException: Text '36/2017' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {WeekOfWeekBasedYear[WeekFields[MONDAY,4]]=36, Year=2017, DayOfWeek=1},ISO of type java.time.format.Parsed

有什么想法吗? 谢谢!

【问题讨论】:

  • 如果可能,请提供堆栈跟踪(您应该这样做,但您询问的任何例外情况)。
  • 提示:向输入数据的发布者介绍标准 ISO 8601 week date 格式:2017-W36
  • 提示:ThreeTen-Extra 项目中的YearWeek 类。

标签: java date java-time


【解决方案1】:

来自文档:https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

如果您使用周数,则应使用大写 Y。

public static void main(String[] args) {
    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("w/YYYY")
            .parseDefaulting(ChronoField.DAY_OF_WEEK, 1)
            .toFormatter();
    LocalDate date = LocalDate.parse("36/2017", formatter);
}

【讨论】:

    【解决方案2】:

    模式错误。您必须设置以下字符串

    “w/YYYY”

    DateTimeFormatter formatter = new 
    DateTimeFormatterBuilder()
                    .appendPattern("w/YYYY")
                    .parseDefaulting(ChronoField.DAY_OF_WEEK, 1)
                    .toFormatter();
    LocalDate date = LocalDate.parse("36/2017", formatter);
    

    【讨论】:

      猜你喜欢
      • 2017-05-12
      • 2021-09-15
      • 1970-01-01
      • 2021-09-06
      • 2019-02-25
      • 2012-08-22
      • 1970-01-01
      • 2013-01-21
      相关资源
      最近更新 更多