简体   繁体   English

如何将字符串转换为DateTime格式?

[英]How to convert a String into DateTime format?

I have a "May 07, 2015" string. 我有一个“ 2015年5月7日”字符串。 I want to convert it to DateTime format as 2015-05-07 pattern . 我想将其转换为DateTime格式为2015-05-07 pattern。
I have converted as follows: 我的转换如下:

scala> val format = new java.text.SimpleDateFormat("MMM dd, yyyy")
format: java.text.SimpleDateFormat = java.text.SimpleDateFormat@2e2b536d

scala> format.parse("May 07 2015")
res5: java.util.Date = Thu May, 07 00:00:00 IST 2015

What should be the next step to convert the above int 2015-05-07 without writing a map to convert the months to their corresponding numeric values? 在不编写将月份转换为相应的数值的映射的情况下,如何转换上述int 2015-05-07的下一步是什么?

Because you already use SimpleDateFormat why do't you use a second DateFormat to format your date, eg 因为您已经使用过SimpleDateFormat所以为什么不使用第二个DateFormat来格式化日期,例如

val df = new java.text.SimpleDateFormat("yyyy-MM-dd")
df.format(*date*)

To complete your example: 要完成您的示例:

val format = new java.text.SimpleDateFormat("MMM dd yyyy")
val myDate = format.parse("May 07 2015")
val df = new java.text.SimpleDateFormat("yyyy-MM-dd")
df.format(myDate)

You have parsed the string now you have to format it for that create a new SimpleDateFormat object with your required format and use format method to format the date. 您已经解析了字符串,现在必须对其进行格式化,以使用所需的格式创建一个新的SimpleDateFormat对象,并使用format方法来格式化日期。

scala> val format = new java.text.SimpleDateFormat("MMM dd yyyy")
format: java.text.SimpleDateFormat = java.text.SimpleDateFormat@2e2b536d

scala> format.parse("May 07 2015")
res0: java.util.Date = Thu May 07 00:00:00 IST 2015

scala> val format1 = new java.text.SimpleDateFormat("yyyy-MM-dd")
format1: java.text.SimpleDateFormat = java.text.SimpleDateFormat@f67a0200

scala> var newDate=format1.format(res0)
newDate: String = 2015-05-07

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM