我正在尝试创建一个函数来检查字符串是否为日期。但是,以下函数出现错误。
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))) { .... }
最佳答案
Try[Date](df.parse(date))
您对此处的类型不感兴趣,因为您忽略了它。所以简单地省略类型参数。尝试(df.parse(date))
。- 您的函数可以更短。
尝试(df.parse(date)).isSuccess
而不是模式匹配。 如果您的环境包含 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/