gpt4 book ai didi

java - Scala:为什么 java.lang.IllegalArgumentException:无法将给定对象格式化为日期?

转载 作者:行者123 更新时间:2023-11-29 06:51:28 25 4
gpt4 key购买 nike

我有以下导致我无法解释的 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)

最佳答案

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

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

有了这个,输出将是:

2017.10.17

关于java - Scala:为什么 java.lang.IllegalArgumentException:无法将给定对象格式化为日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46789326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com