Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
940 views
in Technique[技术] by (71.8m points)

scala - Date conversion

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.ClassCastException:
java.lang.String cannot be cast to java.util.Date
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...