【问题标题】:How do I validate a timestamp in scala?如何在 scala 中验证时间戳?
【发布时间】:2015-11-04 19:47:52
【问题描述】:

我的应用程序接受像这样的字符串“2002-10-15 10:55:01.000000”。我需要在 scala 脚本中验证该字符串对于 db2 时间戳是否有效。

【问题讨论】:

标签: scala


【解决方案1】:

一般来说(我猜)你会用 java.text.DateFormatjoda.time.DateTimeFormat (见 Joda time)以与 java 中相同的方式来做。

一个简单的例子:

import java.text.SimpleDateFormat
import java.util.Date

import scala.util.Try

val date = "2002-10-15 10:55:01.000000"
val formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSS")

val test = Try[Date](formatter.parse(date))

会给你:

test: scala.util.Try[java.util.Date] = Success(Tue Oct 15 10:55:01 CEST 2002)

那么你可以匹配:

test match {
    case Success(date) => // ok
    case Failure(exception) => // not ok
}

【讨论】:

  • 嘿,我们能否从上述结果中仅检索“成功”或“失败”之类的状态,我尝试 test.take(7) 仅检索状态,但它说 test.scala:13: error : value take 不是 scala.util.Try[java.util.Date] if (test.take(7)=="Success") 的成员 ^ 发现一个错误
  • Try 的工作方式很像通常的try-catch-block,包裹在Option 或更确切地说是Either。所以,Try.apply[Date] 的结果要么是Success(date: Date),要么是Failure(ex: _ <: Throwable)。您可以使用test.isSuccesstest.isFailure 检查Try 是否成功。但是,使用match,您还可以查看Success 内部以获取实际解析的Date
【解决方案2】:

你应该在 scala 中使用 SimpleDateFormat 的 java 来做到这一点:

 object DateParser {
      def isValid(f : String, d : String) = {
        try {
          val format = new java.text.SimpleDateFormat(f)
          format.parse(d)
        }catch(java.text.ParseException e) {
          false
        }
      }
      def main(args : Array[String]) {
        val format = "yyyy-MM-dd k:m:s"
        println(isValid(format,"2002-10-15 10:55:01.000000"))
        println(isValid(format,"2002-10-1510:55:01.000000"))
      }
    }

【讨论】:

    猜你喜欢
    • 2011-08-19
    • 2012-09-07
    • 2016-08-05
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 2022-01-08
    • 2021-12-01
    • 2016-05-29
    相关资源
    最近更新 更多