【问题标题】:Scala: Why java.lang.IllegalArgumentException: Cannot format given Object as a Date?Scala:为什么 java.lang.IllegalArgumentException:无法将给定的对象格式化为日期?
【发布时间】:2017-10-17 11:43:07
【问题描述】:

我有以下简单的代码会导致我无法解释的RuntimeException 错误:

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()))
  }
}  

...以及由此产生的运行时错误:

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)

【问题讨论】:

    标签: java scala date date-formatting


    【解决方案1】:

    发生这种情况是因为您将Array 传递给format 方法。您可以直接使用Date

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

    这样,输出将是:

    2017.10.17

    【讨论】:

      【解决方案2】:

      您不需要用数组包装 MessageFormat.format() 的第二个参数,因为它需要一个可变参数。

      使用数组调用令人困惑。目前尚不清楚 Array 是 vararg (Object...) 还是只是 vararg (Object) 的第一个参数。它使用第二个,您会遇到异常。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-01
        • 2017-05-22
        • 1970-01-01
        相关资源
        最近更新 更多