问题描述
最近开始使用WEB UI。并遇到了日期字符串
解析/验证的问题。 dd-mm-yyyy
我发现的一些方法是:
Started working with WEB UI recently. And encountered a problem of date stringparsing/validation. "dd-mm-yyyy"Some approaches I found are:
-
匹配 - 不完整验证,不灵活。
Matching - not complete validation, not flexible.
(19 | 20)\\\ [ - /.](0[1-9]|1[012] )[ - /。](0 [1-9] | [12] [0-9] | 3 [01])
有一篇文章,其中有人建议使用可能的日期字符串预初始化Set - 快速,有效,但也不灵活且耗费内存
There was a post where guy suggest to preinitialize Set with possible date string - fast, valid, but also not flexible and memory consuming
是否有更容易的东西,可能在公共库中可用?
Is there something easier, maybe available in public libs ?
请不要建议SimpleDateFormat :)
UPDATE
for java 8正确答案
是
推荐答案
如果您正在使用java 8然后是什么你在找。 javadoc的链接还包含示例代码和许多预定义格式。除此之外,您还可以定义自己的。
If you are using java 8 then DateTimeFormatter is what you are looking for. The link to javadoc also contains sample code and a number of predefined formats. Besides you can also define your own.
以下是一些代码,来自同一链接的示例:
Here is some code, an example from the same link:
LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);
此外,问题有一些很棒的答案。
Also, this How to parse/format dates with LocalDateTime? (Java 8) question has got some fantastic answers.
编辑:感谢Basil Bourque 有关项目的更新,以防万一需要使用与java提供的功能几乎相同的功能8在某些旧版本的java中。
Thanks Basil Bourque for the updates about ThreeTen-Backport project in case one needs to use almost the same features as provided by java 8 in some older versions of java.
这篇关于根据格式验证字符串日期为有效日期的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!