开发者

Date conversion

开发者 https://www.devze.com 2023-02-18 13:47 出处:网络
I have a date variable var date: Date = new Date() then I have converted this date to String: var dateStr = date.toString()

I have a date variable

var date: Date = new Date()

then I have converted this date to String:

var dateStr = date.toString()

now I need to convert back this String to date. I have tried both:

1:

   var stringToDate: Date = date2Str.asInstanceOf[Date]

and 2:

stringToDate: Date = new SimpleDateFormat("dd.MM.yyyy").parse(dateStr);

But in both case I got the error:

java.lang.ClassCastExcept开发者_如何学Goion:
java.lang.String cannot be cast to java.util.Date


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


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:

  • This is part of the standard library (no need for third party dependencies)
  • This is meant to replace the old 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.


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.


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"))
0

精彩评论

暂无评论...
验证码 换一张
取 消