Reputation: 29159
I'm trying to create a function to check if a string is a date. However, the following function got the error.
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:
[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))) { .... }
Upvotes: 2
Views: 2054
Reputation: 1766
Try[Date](df.parse(date))
You are not interested in type here because you ignore it. So simply omit type parameter. Try(df.parse(date))
.Try(df.parse(date)).isSuccess
instead pattern matching.If your environment contains java 8 then use java.time
package always.
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
Upvotes: 7