【问题标题】:How to check if String contains a date in a SimpleDateFormat and retrieve the date? [duplicate]如何检查字符串是否包含 SimpleDateFormat 中的日期并检索日期? [复制]
【发布时间】:2015-09-12 05:03:48
【问题描述】:

到目前为止我的代码:

String string = "Temp_2014_09_19_01_00_00.csv"  
SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd");

如何检查字符串是否包含日期?我怎样才能找回这个日期?有什么方向吗?

【问题讨论】:

    标签: java string date contains simpledateformat


    【解决方案1】:

    这是一个使用正则表达式做你想做的事情的简单例子(你可能想自己研究正则表达式):

    public static void main(String[] args) throws FileNotFoundException, ParseException {
        String string = "Temp_2014_09_19_01_00_00.csv";
        SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd");
        Pattern p = Pattern.compile("\\d\\d\\d\\d_\\d\\d_\\d\\d");
        Matcher m = p.matcher(string);
        Date tempDate = null;
        if(m.find())
        {
            tempDate = format.parse(m.group());
        }
        System.out.println("" + tempDate);
    }
    

    正则表达式查找4digits_2digits_2digits,然后如果找到匹配项并尝试将其转换为日期,它将获取该匹配项。如果找不到匹配项,则 tempDate 将是 null。如果您想引入timestamp,您也可以这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      相关资源
      最近更新 更多