【发布时间】:2015-11-04 19:47:52
【问题描述】:
我的应用程序接受像这样的字符串“2002-10-15 10:55:01.000000”。我需要在 scala 脚本中验证该字符串对于 db2 时间戳是否有效。
【问题讨论】:
-
你可能想看看this question。
标签: scala
我的应用程序接受像这样的字符串“2002-10-15 10:55:01.000000”。我需要在 scala 脚本中验证该字符串对于 db2 时间戳是否有效。
【问题讨论】:
标签: scala
一般来说(我猜)你会用 java.text.DateFormat 或 joda.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
}
【讨论】:
try-catch-block,包裹在Option 或更确切地说是Either。所以,Try.apply[Date] 的结果要么是Success(date: Date),要么是Failure(ex: _ <: Throwable)。您可以使用test.isSuccess 或test.isFailure 检查Try 是否成功。但是,使用match,您还可以查看Success 内部以获取实际解析的Date。
你应该在 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"))
}
}
【讨论】: