How to convert String to date time in Scala?
Solution 1:
If you are using Java's util.Date then like in java:
val format = new java.text.SimpleDateFormat("yyyy-MM-dd")
format.parse("2013-07-06")
docs for formating - SimpleDateFormat
or if you are using joda's DateTime, then call parse method:
DateTime.parse("07-06-2013")
docs - DateTime
Solution 2:
My go-to option is to use nscala-time: https://github.com/nscala-time/nscala-time
Add this to your build.sbt if using sbt.
libraryDependencies += "com.github.nscala-time" %% "nscala-time" % "1.8.0"
Import and parse your date.
import com.github.nscala_time.time.Imports._
DateTime.parse("2014-07-06")
Solution 3:
For Scala 2.11.8 (Java 1.8.0_162)
import java.time._
import java.time.format.DateTimeFormatter
val datetime_format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
val date_int_format = DateTimeFormatter.ofPattern("yyyyMMdd")
val last_extract_value="2018-05-09 10:04:25.375"
last_extract_value: String = 2018-05-09 10:04:25.375
//String to Date objects
val string_to_date = datetime_format.parse(last_extract_value)
java.time.temporal.TemporalAccessor = {},ISO resolved to 2018-05-08T21:01:15.402
//Date Back to string
date_int_format.format(string_to_date)
res18: String = 20180508