Reputation: 970
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?
Upvotes: 0
Views: 1745
Reputation: 7919
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
Upvotes: 0
Reputation: 9954
Because you already use SimpleDateFormat
why do't you use a second DateFormat
to format your date, e.g.
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)
Upvotes: 3