我的电梯应用程序中有一个日期输入框,我想检查用户输入的日期格式是否正确:dd/mm/yyyy.
如何在scala中为此编写正则表达式检查?我看过模式匹配示例 - 但这看起来过于复杂.
PS:我不必使用正则表达式,欢迎任何其他选择!
Kev*_*ght 13
SimpleDateFormat是非常丑陋的(更令人不安的是)非线程安全的.如果你试图在2个或更多线程中同时使用相同的实例,那么期望事情以最令人不愉快的方式爆炸.
JodaTime更好:
import org.joda.time.format._
val fmt = DateTimeFormat forPattern "dd/MM/yyyy"
val input = "12/05/2009"
val output = fmt parseDateTime input
Run Code Online (Sandbox Code Playgroud)
如果它抛出IllegalArgumentException,则日期无效.
因为我怀疑你想知道实际日期是否有效,你可能想要返回一个Option[DateTime],None如果它是无效的.
def parseDate(input: String) = try {
Some(fmt parseDateTime input)
} catch {
case e: IllegalArgumentException => None
}
Run Code Online (Sandbox Code Playgroud)
或者,Either如果无法格式化,则使用an 捕获实际异常:
def parseDate(input: String) = try {
Right(fmt parseDateTime input)
} catch {
case e: IllegalArgumentException => Left(e)
}
Run Code Online (Sandbox Code Playgroud)
UPDATE
那么使用Either,你有两个主要的策略:
映射双方之一:
parseDate(input).left map (_.getMessage)
//will convert the Either[IllegalArgumentException, DateTime]
//to an Either[String, DateTime]
Run Code Online (Sandbox Code Playgroud)
折起来:
parseDate(input) fold (
_ => S.error(
"birthdate",
"Invalid date. Please enter date in the form dd/mm/yyyy."),
dt => successFunc(dt)
)
Run Code Online (Sandbox Code Playgroud)
当然,这两个可以组成:
parseDate(input).left map (_.getMessage) fold (
errMsg => S.error("birthdate", errMsg), //if failure (Left by convention)
dt => successFunc(dt) //if success (Right by convention)
)
Run Code Online (Sandbox Code Playgroud)