【问题标题】:Parsing date in scala (java time api)在scala中解析日期(java时间api)
【发布时间】:2017-08-03 02:42:02
【问题描述】:

您好,我正在尝试在 scala 中解析带有日期的字符串。我尝试了以下方式:

    import java.time.format.DateTimeFormatter
   import java.time.LocalDateTime
    val date="20 October 2015"
    val formatter=DateTimeFormatter.ofPattern("dd MMMM yyyy")
    val dt=LocalDateTime.parse(ts,formatter)

但我得到以下异常:

java.time.format.DateTimeParseException: Text '20 october 2015' could not be parsed at index 3
  at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
  at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
  at java.time.LocalDateTime.parse(LocalDateTime.java:492)
  ... 29 elided 

为了解析,我使用了标准 Java API 的 DateTimeFormatterLocalDateTime

【问题讨论】:

  • 这里的ts是什么?? val dt=LocalDateTime.parse(ts,formatter)
  • 请包含足够的代码让我们重现该问题,或者至少获得更多上下文。
  • 您没有显示您的ts 字符串,但它似乎有一个解析器不喜欢的小写october - October 工作正常。

标签: java scala datetime java-8


【解决方案1】:

使用

val dt=LocalDate.parse(date,formatter)

而不是 LocalDateTime,因为您的日期字符串不包含任何时间信息。

【讨论】:

  • 不能解决问题:scala> val dt=LocalDate.parse(ts,formatter) java.time.format.DateTimeParseException: Text '24 December 2016' could not be parsed at index 3 at java .time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) 在 java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) 在 java.time.LocalDate.parse(LocalDate.java:400)
  • 这很奇怪,“2016 年 12 月 24 日”对我有用。你有非英语系统语言吗?您能否尝试使用语言环境构建格式化程序: val formatter=DateTimeFormatter.ofPattern("dd MMMM yyyy").withLocale(Locale.US)
【解决方案2】:

您对LocalDateLocalDateTimeLocalDateTimeYearMonthDayTimes 一起使用感到困惑,例如:

println(LocalDateTime.now())
> 2017-03-13T15:11:42.559

LocalDateYearMonthDay 一起使用而没有时间,例如:

println(LocalDate.now())
> 2017-03-13

作为您的示例,您应该使用:LocalDate 来解析 time 文本,例如:

LocalDate.parse(date,formatter)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多