简体   繁体   中英

How to convert a String into DateTime format?

I have a "May 07, 2015" string. I want to convert it to DateTime format as 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?

Because you already use SimpleDateFormat why do't you use a second DateFormat to format your date, eg

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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