1
votes

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))) { .... }
2
you imported java.sql._ - so test has the type Try[java.sql.date] - try replacing that import with import java.util.DateTzach Zohar
I will need Java.sql. so I guess I will need the full quoted type name.ca9163d9

2 Answers

7
votes
  1. 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)).
  2. Your function could be shorter. Try(df.parse(date)).isSuccess instead pattern matching.
  3. 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
    
0
votes

use this: import java.util.Date