简体   繁体   中英

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?

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)
  }
}

How do I format the above string into a sql timestamp? Is there any library which can parse into the necessary format?

The problem is in your pattern actually:

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))
  }
}

In the above example, you were expecting the pattern to be MM, but you were passing M in the datetimeformatter.

To correct you example:

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))
  }
}

Using the above formatter will fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM