49

I am new to Scala and I've learned it for the last few days. I have a doubt about Scala's date converting from string.

How to convert String to Date and time using Scala ?

Does it work the same way as Java?

When I do it that way, I get a compiler error and I can't convert that into Scala because I am new to Scala. And I know that it's not good to convert Java to Scala...

Please share your answer.

smac89
  • 39,374
  • 15
  • 132
  • 179
Prasanth A R
  • 4,046
  • 9
  • 48
  • 76
  • 2
    Yep.. it works in the same way as in Java.. http://stackoverflow.com/a/5377949/920271 – Shrey Jun 08 '13 at 06:04

3 Answers3

61

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

Jukka Dahlbom
  • 1,740
  • 2
  • 16
  • 23
4lex1v
  • 21,367
  • 6
  • 52
  • 86
  • 2
    Is there any package in scala library containing implicits of this conversion? Something like Duration. – Jatin Jun 08 '13 at 08:18
  • 2
    @Jatin no, but you can write it by yourself: `implicit def str2date(str: String) = DateTime.parse(str)` – 4lex1v Jun 08 '13 at 16:32
  • If you plan to have more than one execution thread on your application, you shouldn't use `SimpleDateFormat`, nor `java.util.Date`, since they are not thread-safe (caveat is valid for Java 7-). In this case, consider `joda.time`. – mlg Jul 13 '16 at 03:36
6

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")
BushMinusZero
  • 1,202
  • 16
  • 21
5

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
Vijay Krishna
  • 1,037
  • 13
  • 19