How to check if string matches date pattern using time API?(如何使用Time API检查字符串是否与日期模式匹配?)
问题描述
我的程序正在将输入字符串解析为LocalDate
对象。在大多数情况下,字符串看起来像30.03.2014
,但偶尔看起来像3/30/2014
。根据具体情况,我需要使用不同的模式来调用DateTimeFormatter.ofPattern(String pattern)
。基本上,在进行解析之前,我需要检查字符串是否与模式dd.MM.yyyy
或M/dd/yyyy
匹配。
正则表达式方法类似于:
LocalDate date;
if (dateString.matches("^\d?\d/\d{2}/\d{4}$")) {
date = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("M/dd/yyyy"));
} else {
date = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("dd.MM.yyyy"));
}
这是可行的,但在匹配字符串时最好也使用日期模式字符串。
有没有使用新的Java 8 Time API而不求助于正则表达式匹配来实现这一点的标准方法?我已在文档中查找DateTimeFormatter
,但未找到任何内容。
推荐答案
好的,我会继续并将其作为答案发布。一种方法是创建将保存模式的类。
public class Test {
public static void main(String[] args){
MyFormatter format = new MyFormatter("dd.MM.yyyy", "M/dd/yyyy");
LocalDate date = format.parse("3/30/2014"); //2014-03-30
LocalDate date2 = format.parse("30.03.2014"); //2014-03-30
}
}
class MyFormatter {
private final String[] patterns;
public MyFormatter(String... patterns){
this.patterns = patterns;
}
public LocalDate parse(String text){
for(int i = 0; i < patterns.length; i++){
try{
return LocalDate.parse(text, DateTimeFormatter.ofPattern(patterns[i]));
}catch(DateTimeParseException excep){}
}
throw new IllegalArgumentException("Not able to parse the date for all patterns given");
}
}
您可以像@MenoHochschild那样改进这一点,方法是从您传入的String
数组直接创建DateTimeFormatter
数组。
另一种方法是使用DateTimeFormatterBuilder
,附加您想要的格式。可能还有其他方法,我没有深入阅读文档:-)
DateTimeFormatter dfs = new DateTimeFormatterBuilder()
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
.appendOptional(DateTimeFormatter.ofPattern("dd.MM.yyyy"))
.toFormatter();
LocalDate d = LocalDate.parse("2014-05-14", dfs); //2014-05-14
LocalDate d2 = LocalDate.parse("14.05.2014", dfs); //2014-05-14
这篇关于如何使用Time API检查字符串是否与日期模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用Time API检查字符串是否与日期模式匹配?


- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 转换 ldap 日期 2022-01-01
- 获取数字的最后一位 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01