1

I have the following simple code that leads to a RuntimeException error that I can't explain:

import java.text.MessageFormat
import java.util.Date
import org.apache.commons.cli._
import org.joda.time._
import org.joda.time.format.DateTimeFormat

object TestMain {
  def doFormat(value: Any): String = {
    val ClassOfDouble = classOf[Double]
    val ClassOfDate = classOf[Date]
    val ClassOfDateTime = classOf[DateTime]
    val result: String = value.getClass match {
      case ClassOfDouble => MessageFormat.format("{0,number,#.####################}", Array(value.asInstanceOf[DateTime]))
      case ClassOfDate => MessageFormat.format("{0,date,yyyy.MM.dd}", Array(value.asInstanceOf[Date]))
      case ClassOfDateTime => DateTimeFormat.forPattern("yyyy.MM.dd HH:mm:SSS").print(value.asInstanceOf[DateTime])
      case _ => value.toString
    }
    result
  }

  def main(args: Array[String]): Unit = {
    println(doFormat(new Date()))
  }
}  

... and the resulting runtime error:

Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
    at java.text.DateFormat.format(Unknown Source)
    at java.text.Format.format(Unknown Source)
    at java.text.MessageFormat.subformat(Unknown Source)
    at java.text.MessageFormat.format(Unknown Source)
    at java.text.Format.format(Unknown Source)
    at java.text.MessageFormat.format(Unknown Source)
    at test.TestMain$.doFormat(TestMain.scala:28)
    at test.TestMain$.main(TestMain.scala:39)
    at test.TestMain.main(TestMain.scala)

2 Answers 2

3

This happens because you're passing an Array to the format method. You can simply use the Date directly:

case ClassOfDate => MessageFormat.format("{0,date,yyyy.MM.dd}", value.asInstanceOf[Date])

With this, the output will be:

2017.10.17

Sign up to request clarification or add additional context in comments.

Comments

3

You don't need to wrap the second argument of the MessageFormat.format() with an Array since it requires a vararg.

Call with Array is confusing. It is unclear if Array is vararg (Object...) or just a first argument of vararg (Object). It uses the second and you encounter with an Exception.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.