加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala / Lift检查日期是否格式正确

发布时间:2020-12-16 08:50:10 所属栏目:安全 来源:网络整理
导读:我的电梯应用程序中有一个日期输入框,我想检查用户输入的日期格式是否正确:dd / mm / yyyy. 如何在scala中为此编写正则表达式检查?我看过模式匹配示例 – 但这看起来过于复杂. PS:我不必使用正则表达式,欢迎任何其他选择! 解决方法 SimpleDateFormat是丑
我的电梯应用程序中有一个日期输入框,我想检查用户输入的日期格式是否正确:dd / mm / yyyy.

如何在scala中为此编写正则表达式检查?我看过模式匹配示例 – 但这看起来过于复杂.

PS:我不必使用正则表达式,欢迎任何其他选择!

解决方法

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

如果它抛出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)
}

UPDATE

要使用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)
)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读