I have a date variable
var date: Date = new Date()
then I have converted this date to String:
var dateStr = date.toString(
Your first try should give you a ClassCastException because you cannot cast.aString to a Date. the second try does not seem to be using the right format that Date.toString() prints. The toString method of java.utility.Date returns a String in the format specified in the javadoc.
Starting Scala 2.11
, targeting Java 8
, the java.time
Date Time API can be used:
import java.time.LocalDate
import java.time.format.DateTimeFormatter
val dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy")
LocalDate.now().format(dtf) // "06-07-2018"
LocalDate.parse("06-07-2018", dtf) // java.time.LocalDate = 2018-07-06
Note that:
java.util.Date
/SimpleDateFormat
api.This is also supposed to replace the widely used joda-time
library:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
And by association nscala-time which is a wrapper around joda-time
.
I see a couple of problems in your code, but this works fine:
scala> val format = new java.text.SimpleDateFormat("dd-MM-yyyy")
format: java.text.SimpleDateFormat = java.text.SimpleDateFormat@9586200
scala> format.format(new java.util.Date())
res4: java.lang.String = 21-03-2011
scala> format.parse("21-03-2011")
res5: java.util.Date = Mon Mar 21 00:00:00 CET 2011
using nscala-time the following worked for me :
import com.github.nscala_time.time._
import com.github.nscala_time.time.Imports._
val ysterday= (DateTime.now- 1.days).toString(StaticDateTimeFormat.forPattern("yyyyMMdd"))