scala Joda.时间DateTimeFormat返回:java. lang.非法参数异常:无效的格式不正确

wfveoks0  于 2023-02-08  发布在  Scala
关注(0)|答案(1)|浏览(172)

我正在将一些日期格式从"ddMMMyyyy"转换为"yyyy-MM-dd"。我编写了以下代码:

import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import scala.util.{Failure, Success, Try}

def dateFormatter(date: String, inpuFormat: String, outputFormat: String): String = {
    var returnDate: String = ""
    val inputDateFormat = DateTimeFormat.forPattern(inpuFormat)
    val outputDateFormat = DateTimeFormat.forPattern(outputFormat)

    Try {
      if (date != null && date.trim != "") {
        val parsedDate = DateTime.parse(date.trim(), inputDateFormat)
        returnDate = outputDateFormat.print(parsedDate)
      } else { returnDate = null }
    } match {
      case Success(_) => { returnDate }
      case Failure(e) => {
        println("exception!" + e)
        date
      }
    }
  }

我用的是scala 2.12
如果作为输入传递:

"09September2032"

然后我得到

"2032-09-09"

不过,如果我通过了

"09sep2032"

我得到了以下异常:

java.lang.IllegalArgumentException: Invalid format: "09sep2032" is malformed at "sep2032"

提供的模式有什么问题?

m1m5dgzv

m1m5dgzv1#

似乎对于九月,我们需要传递4个字符Sept

println(dateFormatter("09Jan2032", "ddMMMyyyy", "yyyy-MM-dd"))
  println(dateFormatter("09Feb2032", "ddMMMyyyy", "yyyy-MM-dd"))
  println(dateFormatter("09Mar2032", "ddMMMyyyy", "yyyy-MM-dd"))
  println(dateFormatter("09Apr2032", "ddMMMyyyy", "yyyy-MM-dd"))
  println(dateFormatter("09May2032", "ddMMMyyyy", "yyyy-MM-dd"))
  println(dateFormatter("09Jun2032", "ddMMMyyyy", "yyyy-MM-dd"))
  println(dateFormatter("09Jul2032", "ddMMMyyyy", "yyyy-MM-dd"))
  println(dateFormatter("09Aug2032", "ddMMMyyyy", "yyyy-MM-dd"))
  println(dateFormatter("09Sept2032", "ddMMMyyyy", "yyyy-MM-dd"))
  println(dateFormatter("09Oct2032", "ddMMMyyyy", "yyyy-MM-dd"))
  println(dateFormatter("09Nov2032", "ddMMMyyyy", "yyyy-MM-dd"))
  println(dateFormatter("09Dec2032", "ddMMMyyyy", "yyyy-MM-dd"))

将输出:

2032-01-09
2032-02-09
2032-03-09
2032-04-09
2032-05-09
2032-06-09
2032-07-09
2032-08-09
2032-09-09
2032-10-09
2032-11-09
2032-12-09

相关问题