scala 日期转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5377790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Date conversion
提问by Echo
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:
1:
var stringToDate: Date = date2Str.asInstanceOf[Date]
and 2:
和 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
回答by Wilfred Springer
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
回答by Xavier Guihot
Starting Scala 2.11, targeting Java 8, the java.timeDate Time API can be used:
开始Scala 2.11,定位Java 8,java.time日期时间 API 可以使用:
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 replacethe old
java.util.Date/SimpleDateFormatapi. This is also supposed to replacethe widely used
joda-timelibrary: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-timewhich is a wrapper around
joda-time.
- 这是标准库的一部分(不需要第三方依赖)
- 这是为了替换旧的
java.util.Date/SimpleDateFormatapi。 这也应该取代广泛使用的
joda-time库:请注意,从 Java SE 8 开始,要求用户迁移到 java.time (JSR-310) - 替代该项目的 JDK 的核心部分。
通过关联nscala-time,它是
joda-time.
回答by krock
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.
您的第一次尝试应该会给您一个 ClassCastException,因为您不能将.aString 转换为日期。第二次尝试似乎没有使用正确的Date.toString()打印格式。java.utility.Date 的 toString 方法以 javadoc 中指定的格式返回一个字符串。
回答by CruncherBigData
using nscala-timethe following worked for me :
使用nscala-time以下对我有用:
import com.github.nscala_time.time._
import com.github.nscala_time.time.Imports._
val ysterday= (DateTime.now- 1.days).toString(StaticDateTimeFormat.forPattern("yyyyMMdd"))

