如何使用Time API检查字符串是否与日期模式匹配? [英] How to check if string matches date pattern using time API?

查看:47
本文介绍了如何使用Time API检查字符串是否与日期模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序正在将输入字符串解析为LocalDate对象。在大多数情况下,字符串看起来像30.03.2014,但偶尔看起来像3/30/2014。根据具体情况,我需要使用不同的模式来调用DateTimeFormatter.ofPattern(String pattern)。基本上,在进行解析之前,我需要检查字符串是否与模式dd.MM.yyyyM/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检查字符串是否与日期模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆