简体   繁体   English

使用不同的格式/模式将字符串解析为日期

[英]Parse string to date using different formats/patterns

I need to parse a string to a date but have no prior knowledge which pattern the string will be in. This is similar to the question How to convert String to Date without knowing the format? 我需要将字符串解析为日期,但不了解字符串将采用哪种模式。这类似于问题, 如何在不知道格式的情况下将字符串转换为日期? .

To solve this I adopted couple of patterns to test the outcome. 为了解决这个问题,我采用了两种模式来测试结果。 However, what I am getting is a bit strange. 但是,我得到的有点奇怪。

Example 1: 范例1:

    import java.util.Date;
    import org.apache.commons.lang3.time.DateUtils;

    public Date extractDate(String dateStr) {

        String [] datePatterns = {"yyyy-MM-dd", "dd-MM-yyyy"};
        Date date = null;

        try {
            date = DateUtils.parseDate(dateStr, datePatterns);
        }
        catch (Exception except) {
                except.printStackTrace();
        }
        return date;
    }



    public static void main(String[] args) throws Exception {
        System.out.println ("2013-09-30:" + extractDate("2013-09-30") );
        System.out.println ("30-09-2013:" + extractDate("30-09-2013") );

    }

This gives: 这给出:

    2013-10-30:Wed Oct 30 00:00:00 EAT 2013
    30-09-2013:Mon Mar 05 00:00:00 EAT 36

The result from parsing '30-09-2013' is obviously strange. 解析“ 30-09-2013”​​的结果显然很奇怪。

Example 2: Here I only switch the pattern 示例2:在这里我仅切换模式

        String [] datePatterns = {"dd-MM-yyyy", "yyyy-MM-dd"};

This gives: 这给出:

    2013-10-30:Mon Mar 05 00:00:00 EAT 36
    30-09-2013:Mon Sep 30 00:00:00 EAT 2013

In example 2 the result from parsing '2013-10-30' is strange. 在示例2中,解析“ 2013-10-30”的结果很奇怪。

How can one parse date strings using different formats/patterns so that the resulting dates are correct? 一个人如何使用不同的格式/模式来分析日期字符串,以使结果日期正确?

Update to use parseDateStrictly . 更新为使用parseDateStrictly When I did this I got the following output: 当我这样做时,我得到以下输出:

2013-09-30:Mon Sep 30 00:00:00 EDT 2013
30-09-2013:Mon Sep 30 00:00:00 EDT 2013

My answer would be same. 我的答案是相同的。 Without any prior knowledge of the format you can't parse date. 没有格式的任何先验知识,您将无法解析日期。

Few examples of writing a date would be: DD-MM-YYYY , MM-DD-YYYY , DD/MM/YYYY , MM/DD/YYYY , MM/DD/YY , DD/MM/YY . 很少有写日期的示例是: DD-MM-YYYYMM-DD-YYYYDD/MM/YYYYMM/DD/YYYYMM/DD/YYDD/MM/YY For only these many types of dates can you find any common pattern? 对于仅这些许多类型的日期,您可以找到任何常见的模式吗?

NO! 没有! Without knowing the format which user enters you can't parse it. 不知道用户输入的格式,就无法解析。

If you come up with pattern matching, a date such as 10-09-2010 which matches with MM-DD-YYYY format and DD-MM-YYYY format too. 如果要提供模式匹配,则日期(例如10-09-2010也将与MM-DD-YYYY格式和DD-MM-YYYY格式匹配。 Here you will have a problem 在这里你会有问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM