3

我尝试LocaDate按格式获取,所以我使用了这个接收日期并搜索要解析的格式的函数:

def getLocalDate(date: String): LocalDate = {

    val pattern1 = DateTimeFormatter.ofPattern("dd MMM, yyyy")
    val pattern2 = DateTimeFormatter.ofPattern("dd MMM yyyy")
    val pattern3 = DateTimeFormatter.ofPattern("yyyy-MMM-dd")
    val pattern4 = DateTimeFormatter.ofPattern("dd/MM/YYYY")
    val pattern5 = DateTimeFormatter.ISO_LOCAL_DATE

    val result = Try {
      LocalDate.parse(date, pattern1)
    } recover {
      case _ => LocalDate.parse(date, pattern2)
    } recover {
      case _ => LocalDate.parse(date, pattern3)
    } recover {
      case _ => LocalDate.parse(date, pattern4)
    } recover {
      case _ => LocalDate.parse(date, pattern5)
    }

    result.get
  }

用法:

var s1 = "01/08/2010"
getLocalDate(s1)

但出现错误:

java.time.format.DateTimeParseException: Text '01/08/2010' could not be parsed at index 0

而且我不知道为什么以及出了什么问题。

4

1 回答 1

5
import java.time.LocalDate
import java.time.format.DateTimeFormatter

import scala.util.Try

def getLocalDate(date: String): java.time.LocalDate = {
  val pattern1 = DateTimeFormatter.ofPattern("dd MMM, yyyy")
  val pattern2 = DateTimeFormatter.ofPattern("dd MMM yyyy")
  val pattern3 = DateTimeFormatter.ofPattern("yyyy-MMM-dd")
  val pattern4 = DateTimeFormatter.ofPattern("dd/MM/yyyy")
  val pattern5 = DateTimeFormatter.ISO_LOCAL_DATE

  val result = Try {
    LocalDate.parse(date, pattern1)
  } recover {
    case _ => LocalDate.parse(date, pattern2)
  } recover {
    case _ => LocalDate.parse(date, pattern3)
  } recover {
    case _ => LocalDate.parse(date, pattern4)
  } recover {
    case _ => LocalDate.parse(date, pattern5)
  }

  result.get
}
var s1 = "01/08/2010"
getLocalDate(s1)

这在 REPL(Scala 2.11.8,Java 1.8)中运行良好。

您的错误是在最后一个模式中包含“YYYY”而不是“yyyy”。另外,看看包 nscala-time。也许它会为您的应用程序提供更好的绑定。

于 2016-08-03T08:45:16.447 回答