【问题标题】:How to convert string 2019-03-29T10:45-05:00[America/Chicago] to localdate?如何将字符串 2019-03-29T10:45-05:00[America/Chicago] 转换为本地日期?
【发布时间】:2019-03-01 23:45:25
【问题描述】:
selectedStart = "2019-03-29T10:45-05:00[America/Chicago]";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate parsedDate = LocalDate.parse(selectedStart, formatter);

我从 tableview 行获取我的 selectedStart 字符串并尝试将其转换为 LocalDate 但我收到错误:

无法解析文本“2019-03-29T10:45-05:00[America/Chicago]”,在索引 10 处找到未解析的文本

我只想要yyyy-MM-dd 格式的日期,不想获取分钟、秒、时区等...

【问题讨论】:

  • selectedStart.substring(0,9)?
  • @MarkusMitterauer 太可怕了。请使用 Time API 进行此类转换。

标签: java formatter localdate


【解决方案1】:

这应该足够了。请注意,我使用完整日期 pattern 进行第一次转换,这是必需的(parse 会抛出 DateTimeParseException)。

final String selectedStart = "2019-03-29T10:45-05:00[America/Chicago]";
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmXXX'['VV']'");
final LocalDate parsedDate = LocalDate.parse(selectedStart, formatter);

【讨论】:

  • 嗨,你的代码是正确的,我得到了我想要的 localDate。但是我忘了提到我不想要一个字符串,我想要一个只有 yyyy-MM-dd 中的日期的 localdate 值,所以我可以将 datepicker 的值设置为该 localdate
  • @AntonioContreras 答案已更新。您只需要“parsedDate”变量。 LocalDate 仅包含日期部分。
  • 私人 DatePicker modifyAppointmentDate; modifyAppointmentDate.setValue(formattedDate);
【解决方案2】:

ZonedDateTime.parse( … ).toLocalDate

您的输入字符串采用标准 ISO 8601 格式,但已扩展为在方括号中附加时区名称。这种扩展格式正是ZonedDateTime 类中默认使用的格式。

ZonedDateTime.parse( "2019-03-29T10:45-05:00[America/Chicago]" ) 

如果您只需要没有时间和时区的日期,请从中提取LocalDate

LocalDate ld = 
    ZonedDateTime.parse( "2019-03-29T10:45-05:00[America/Chicago]" )
                 .toLocalDate() ;

【讨论】:

    猜你喜欢
    • 2019-09-27
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多