1

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:

    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.

Example 2: Here I only switch the pattern

        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.

How can one parse date strings using different formats/patterns so that the resulting dates are correct?

Community
  • 1
  • 1
Mugoma J. Okomba
  • 3,185
  • 1
  • 26
  • 37

2 Answers2

1

Update to use 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
John B
  • 32,493
  • 6
  • 77
  • 98
0

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. 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. Here you will have a problem

NewUser
  • 3,729
  • 10
  • 57
  • 79
  • although your assertion is correct, it does not address the error being demonstrated in the question especially as the two formats provided are mutually exclusive. – John B Oct 09 '13 at 11:09