Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing different date formats in a string in Java

I have a string which can possibly contain a date in any of the following formats:

2001-01-05 (yyyy-mm-dd)
2001/01/05 (yyyy/mm/dd)
01/05/2001 (dd/mm/yyyy)
01-05-2001 (dd-mm-yyyy)
2001 january 5
2001 5 january
january 5 2001
5 january 2001
january 5
5 january

I want to be able to parse the particular string and extract the Date object from it.

My approach was as follows:

String[] date_formats = {
                            "yyyy-MM-dd",
                            "yyyyy/MM/dd", 
                            "dd/MM/yyyyy",
                            "dd-MM-yyyy",
                            "yyyy MMM dd",
                            "yyyy dd MMM",
                            "dd MMM yyyy",
                            "dd MMM",
                            "MMM dd",
                            "dd MMM yyyy"};

String output_date = null;
for (String formatString : date_formats)
{
     try
     {    
         Date mydate = new SimpleDateFormat(formatString).parse(token);
         SimpleDateFormat outdate = new SimpleDateFormat("yyyyMMdd");
         output_date = outdate.format(mydate);
         break;
     }
     catch (ParseException e) {
         System.out.println("Next!");
     }
 }

This doesn't seem to work as expected. Especially for dates like 5 January 2001 etc. How do I go about doing this?

like image 318
Alagappan Ramu Avatar asked Oct 02 '13 12:10

Alagappan Ramu


People also ask

Can we compare dates in string format in Java?

Explanation: Here we are using DateTimeFormatter object to parse the given dates from String type to LocalDate type. Then we are using isEqual(), isAfter() and isBefore() functions to compare the given dates. We can also use the compareTo() function of the LocalDate class to compare the Dates.


2 Answers

Use SimpleDateFormat.setLenient(false). This way it will not attempt to parse dates that aren't the exact format it wants.

like image 186
Kayaman Avatar answered Sep 27 '22 19:09

Kayaman


You need to have all formats in the date_formats array for the type of format you anticipate would be coming in.

Have a look at the SimpleDateFormat javadocs.

Have a look at the examples in the javadocs.

2001-01-05      - yyyy-MM-dd 
2001/01/05      - yyyy/MM/dd
01/05/2001      - dd/MM/yyyy 
01-05-2001      - dd-MM-yyyy 
2001 january 5  - yyyy MMMMM d
2001 5 january  - yyyy d MMMMM
january 5 2001  - MMMMM d yyyy 
5 january 2001  - d MMMMM yyyy
january 5       - MMMMM d
5 january       - d MMMMM
like image 21
JHS Avatar answered Sep 27 '22 18:09

JHS