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

标签 scala

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

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/

相关文章:

scala - spark-csv 包中的 inferSchema

scala - scala 中的函数式编程 - 无限流

scala - 如何订购密封性状?

scala - 按名称和按值类型的多态类型推断

Scala:发现类型不匹配,需要单位: bool

scala - Gatling maven插件错误

scala - 为什么此Scala代码报告编译错误:递归值x需要类型

scala - 如何给 scalaz 的 Functor 赋予具有上下文绑定(bind)的更高种类的类型?

scala - 无法弄清楚 = :=[A, B] 代表什么

scala - 在 DSL 中隐藏和限定隐式变量的创建