Skip to content

Instantly share code, notes, and snippets.

@TJC
Last active March 18, 2022 04:53
Show Gist options
  • Save TJC/2504b2d7d8be1065eae80486382469f0 to your computer and use it in GitHub Desktop.
Save TJC/2504b2d7d8be1065eae80486382469f0 to your computer and use it in GitHub Desktop.
Mysql 5.7 compatible Scala/Java DateTimeFormatter expression
import java.time._
import java.time.format.{DateTimeFormatter, DateTimeFormatterBuilder}
import java.time.temporal.ChronoField._
// This one doesn't work, because Mysql can return five-digits of precision, if the sixth digit was 0
val badFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS")
val mysqlFormatter = new DateTimeFormatterBuilder().appendValue(YEAR, 4)
.appendLiteral('-')
.appendValue(MONTH_OF_YEAR, 2)
.appendLiteral('-')
.appendValue(DAY_OF_MONTH, 2)
.appendLiteral(' ')
.appendValue(HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2)
.optionalStart.appendLiteral(':')
.appendValue(SECOND_OF_MINUTE, 2)
.optionalStart.appendFraction(NANO_OF_SECOND, 1, 6, true)
.toFormatter()
val s = "2022-03-18 13:56:01.857"
val x = LocalDateTime.parse(s, mysqlFormatter)
println(x)
println(f.format(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment