Scala/Lift检查日期格式是否正确 [英] Scala/Lift check if date is correctly formatted
问题描述
我的电梯应用程序中有一个日期输入框,我想检查用户输入的日期格式是否正确: dd/mm/yyyy .
I have a date input box in my lift application, and I want to check that a user-entered date is in correct format: dd/mm/yyyy.
如何在Scala中为此编写正则表达式检查?我看过模式匹配示例-但这似乎太复杂了.
How can I write a regex check for this in scala? I've looked at pattern matching examples - but that seems over-complicated.
PS:我不必使用正则表达式,欢迎使用其他任何替代方法!
PS: I don't have to use regex, any other alternatives are welcome!
推荐答案
SimpleDateFormat
丑陋且(更令人不安的)非线程安全的.如果您尝试同时在2个或更多线程中使用同一实例,则可能会以最不愉快的方式崩溃.
SimpleDateFormat
is ugly and (more disturbingly) non-thread-safe. If you try to simultaneously use the same instance in 2 or more threads then expect things to blow up in a most unpleasant fashion.
JodaTime更好:
JodaTime is far nicer:
import org.joda.time.format._
val fmt = DateTimeFormat forPattern "dd/MM/yyyy"
val input = "12/05/2009"
val output = fmt parseDateTime input
如果抛出IllegalArgumentException
,则日期无效.
If it throws an IllegalArgumentException
, then the date wasn't valid.
由于我怀疑您想知道实际日期是否有效,因此您可能想返回Option[DateTime]
,如果它无效则返回None
.
As I suspect you'll want to know the actual date if it was valid, you may want to return an Option[DateTime]
, with None
if it was invalid.
def parseDate(input: String) = try {
Some(fmt parseDateTime input)
} catch {
case e: IllegalArgumentException => None
}
或者,如果无法格式化,请使用Either
捕获实际的异常:
Alternatively, use an Either
to capture the actual exception if formatting wasn't possible:
def parseDate(input: String) = try {
Right(fmt parseDateTime input)
} catch {
case e: IllegalArgumentException => Left(e)
}
更新
要使用Either
,您有两种主要策略:
To then use the Either
, you have two main tactics:
映射两侧之一:
parseDate(input).left map (_.getMessage)
//will convert the Either[IllegalArgumentException, DateTime]
//to an Either[String, DateTime]
折叠:
parseDate(input) fold (
_ => S.error(
"birthdate",
"Invalid date. Please enter date in the form dd/mm/yyyy."),
dt => successFunc(dt)
)
当然,两者可以组成:
parseDate(input).left map (_.getMessage) fold (
errMsg => S.error("birthdate", errMsg), //if failure (Left by convention)
dt => successFunc(dt) //if success (Right by convention)
)
这篇关于Scala/Lift检查日期格式是否正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!