对任何常规输入使用DateTimeFormatter

时间:2019-01-16 15:39:20

标签: java scala

我需要与数据库进行交互,因此我正在使用ZonedDateTime在sql时间戳和即时之间进行转换,但是我似乎无法使其正常工作。我已经看到了其他解决方案,其中涉及先将时间戳转换为“ LocalDate”或“ LocalDateTime”,然后再转换为“ ZonedDateTime”,但是我的转换器应该可以采用两种方法;我不必明确声明要将时间戳转换为第一个时间戳。关于编写通用时间戳转换器的任何提示?代码在这里:

class ConvertTimestamp(form: String, parser: DateTimeFormatter) extends ObjectConversion[Any] with FormattedConversion[DateTimeFormatter] {
    def this(form: String) = this(form, DateTimeFormatter.ofPattern(form).withZone(ZoneOffset.UTC))

    def execute(input: String): Timestamp = {
        val timeStamp = parsers.iterator
           .map( f => {
              val zdt = ZonedDateTime.parse(input, f)
              Try(Timestamp.from(zdt.toInstant))
           })
           .find(_.isSuccess)
           .flatMap(._toOption)

        timeStamp getOrElse { throw new Exception("Can't parse")  


    def parsers: Array[DateTimeFormatter] = Array(parser)
}

还有一个示例调用:

 new ConvertTimestamp("YYYY-MM-dd HH:mm:ss").execute("2000-01-01 12:00:00")

应该等于

 Timestamp.valueOf(LocalDateTime.parse("2000-01-01T12:00:00"))

但此呼叫失败,显示

java.time.format.DateTimeParseException: Text '2000-01-01 12:00:00' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {DayOfMonth=1, WeekBasedYear[WeekFields[SUNDAY,1]]=2000, MonthOfYear=1},ISO,Z resolved to 12:00 of type java.time.format.Parsedd

0 个答案:

没有答案