我的lift应用程序中有一个日期输入框,我想检查用户输入的日期是否格式正确:dd/mm/yyyy。
如何在scala中为此编写regex检查?我看过模式匹配的例子--但这似乎太复杂了。
PS:我不需要使用regex,任何其他的选择都是受欢迎的!
发布于 2011-05-17 16:01:24
SimpleDateFormat是丑陋和(更令人不安的)非线程安全。如果您试图在两个或多个线程中同时使用相同的实例,那么期望事情以一种最令人不快的方式爆炸。
JodaTime要好得多:
import org.joda.time.format._
val fmt = DateTimeFormat forPattern "dd/MM/yyyy"
val input = "12/05/2009"
val output = fmt parseDateTime input如果它抛出一个IllegalArgumentException,则日期无效。
正如我所怀疑的,如果实际日期是有效的,您可能想知道它的实际日期,您可能希望返回一个Option[DateTime],如果它是无效的,则返回一个None。
def parseDate(input: String) = try {
Some(fmt parseDateTime input)
} catch {
case e: IllegalArgumentException => None
}或者,如果不可能设置格式,则使用Either捕获实际异常:
def parseDate(input: String) = try {
Right(fmt parseDateTime input)
} catch {
case e: IllegalArgumentException => Left(e)
}更新
然后使用Either,您有两个主要策略:
绘制双方之一的地图:
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)
)发布于 2011-05-17 16:01:46
正如用户未知所写的,您应该使用一些知道如何正确处理日期的库,包括每个月的天数和闰年。
对于字段的滚动,SimpleDateFormat不是很直观,一开始只在其他字段上滚动就可以接受错误的日期。要阻止它这样做,您必须在其上调用setLenient(false)。还要记住,SimpleDateFormat并不是线程安全的,所以每次想使用它时都需要创建一个新实例:
def validate(date: String) = try {
val df = new SimpleDateFormat("dd/MM/yyyy")
df.setLenient(false)
df.parse(date)
true
} catch {
case e: ParseException => false
}或者,您也可以使用Joda时间,它比Java更加直观,并提供了线程安全的日期格式:
val format = DateTimeFormat.forPattern("dd/MM/yyyy")
def validate(date: String) = try {
format.parseMillis(date)
true
}
catch {
case e: IllegalArgumentException => false
}发布于 2016-06-19 08:31:09
在对象中定义DateTimeFormatter实例是一个很好的实践,因为它是线程安全和不可变的。
object DateOfBirth{
import org.joda.time.format.DateTimeFormat
import scala.util.Try
val fmt = DateTimeFormat forPattern "MM/dd/yyyy"
def validate(date: String) = Try(fmt.parseDateTime(date)).isSuccess
}https://stackoverflow.com/questions/5982484
复制相似问题