gpt4 book ai didi

scala - 找到 java.util.Date 但需要 java.sql.Date?

转载 作者:行者123 更新时间:2023-12-01 22:17:17 25 4
gpt4 key购买 nike

我正在尝试创建一个函数来检查字符串是否为日期。但是,以下函数出现错误。

import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
import java.sql._
import scala.util.{Success, Try}

def validateDate(date: String): Boolean = {
val df = new java.text.SimpleDateFormat("yyyyMMdd")
val test = Try[Date](df.parse(date))
test match {
case Success(_) => true
case _ => false
}
}

错误:

[error] C:\Users\user1\IdeaProjects\sqlServer\src\main\scala\main.scala:14: type mismatch;[error]  found   : java.util.Date[error]  required: java.sql.Date[error]       val test = Try[Date](df.parse(date))[error]                                    ^[error] one error found[error] (compile:compileIncremental) Compilation failed[error] Total time: 2 s, completed May 17, 2017 1:19:33 PM

Is there a simpler way to validate if a string is a date without create a function?

The function is used to validate the command line argument.

if (args.length != 2 || validateDate(args(0))) { .... }

最佳答案

  1. Try[Date](df.parse(date)) 您对此处的类型不感兴趣,因为您忽略了它。所以简单地省略类型参数。 尝试(df.parse(date))
  2. 您的函数可以更短。 尝试(df.parse(date)).isSuccess而不是模式匹配。
  3. 如果您的环境包含 java 8,则始终使用 java.time 包。

    import scala.util.Try
    import java.time.LocalDate
    import java.time.format.DateTimeFormatter

    // Move creation of formatter out of function to reduce short lived objects allocation.
    val df = DateTimeFormatter.ofPattern("yyyy MM dd")

    def datebleStr(s: String): Boolean = Try(LocalDate.parse(s,df)).isSuccess

关于scala - 找到 java.util.Date 但需要 java.sql.Date?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44031319/

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