【问题标题】:How to format a date time string of format "3/22/2018 12:24:29 PM" into sql timestamp to insert into h2 in memory database?如何将格式为“3/22/2018 12:24:29 PM”的日期时间字符串格式化为sql时间戳以插入内存数据库中的h2?
【发布时间】:2018-07-04 02:17:20
【问题描述】:
import java.time.format.DateTimeFormatter
import java.sql.Timestamp
object SetSuite {
  def main(args: Array[String]) {
    val date = "3/22/2018 12:24:29 PM"

    var formatter = DateTimeFormatter.ofPattern( "MM/dd/yyyy h:mm:ss a" );
    println(formatter.parse(date)
  }
}

如何将上面的字符串格式化成sql时间戳?有没有可以解析成必要格式的库?

【问题讨论】:

  • 对于测试,您可以从阅读 Acolyte 中受益,这将有助于设置完全隔离的持久性 JDBC。

标签: scala unit-testing timestamp h2 scalatest


【解决方案1】:

问题实际上出在你的模式中:

import java.time.format.DateTimeFormatter
object SetSuite {
  def main(args: Array[String]) {
    val date = "03/22/2018 12:24:29 PM" //Note-Here

    var formatter = DateTimeFormatter.ofPattern( "MM/dd/yyyy h:mm:ss a" )
    println(formatter.parse(date))
  }
}

在上面的示例中,您希望模式为 MM,但您在 datetimeformatter 中传递了 M。

纠正你的例子:

import java.time.format.DateTimeFormatter
object SetSuite {
  def main(args: Array[String]) {
    val date = "3/22/2018 12:24:29 PM"

    var formatter = DateTimeFormatter.ofPattern( "M/dd/yyyy h:mm:ss a" ) //Note-Here
    println(formatter.parse(date))
  }
}

使用上述格式化程序将修复它。

【讨论】:

  • 我尝试了您建议的格式,但我仍然面临这个问题。这是异常:java.time.format.DateTimeParseException: Text '3/22/2018 12:24:29 PM' could not be parse, unparsed text found
  • @ChandrakanthK,您是否运行了上述相同的程序?
猜你喜欢
  • 2019-06-06
  • 1970-01-01
  • 2019-01-18
  • 2012-04-12
  • 1970-01-01
  • 2013-04-16
  • 1970-01-01
  • 1970-01-01
  • 2012-09-07
相关资源
最近更新 更多