Scala String to Java Util Date Conversion

Prasanth A R picture Prasanth A R · Aug 27, 2013 · Viewed 10.2k times · Source

Hi the Conversion of String to Date is not possible here..

I search and use several methods but the error can not change..

here the date format is var q and convert that to formatedDate that is String

then the String convert into util date..

SearchDate is from method parameter and the value of SearchDate is "Thu Aug 29 00:00:00 IST 2013"

    var q: Date = SearchDate
    var dateStr = q.toString()
    var formatter: DateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy")
    var dat = formatter.parse(dateStr)
    var cal: Calendar = Calendar.getInstance()
    cal.setTime(dat)
    var formatedDate = cal.get(Calendar.DATE) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.YEAR)
    println("formatedDate : " + formatedDate)
    val date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(dateStr)// Error Occured Here..

the error is

Exception in thread "main" java.text.ParseException: Unparseable date: "Thu Aug 29 00:00:00 IST 2013" at java.text.DateFormat.parse(Unknown Source)

please share your answers ..

Answer

soulcheck picture soulcheck · Aug 27, 2013

You're trying to parse "E MMM dd HH:mm:ss Z yyyy" formatted date string as "yyyy-MM-dd HH:mm" formatted one, in this line:

val date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(dateStr)

No wonder it fails.

Maybe you took the wrong date format for second SimpleDateFormat instance by mistake? Or maybe you're passing wrong parameter to parse() ?

edit

It looks like you actually wanted to call:

val date = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(dat)