0

I am trying to compare two dates in java. While the following code works fine, I would like to handle situations where there may be some alterations in the date format of the input dates.

For example, in the below code, the date format of the two dates are as yyyy/mm/dd hh:mm:ss am. But sometimes there are some additional white space/new line characters found in the input date and this causes exception.

java.text.ParseException: Unparseable date: "02/14/2013
    07:00:00 AM"      

The following is the code am trying to execute.

        try 
        {
            Date date1 = (Date)DATE_FORMAT_yyyy_mm_dd_hh_mm_ss.parse(slaTime); // usually the data comes as 2013/02/03 09:09:09 AM
            Date date2 = (Date)DATE_FORMAT_yyyy_mm_dd_hh_mm_ss.parse(actualTime);// usually the data comes as 2013/02/03  09:06:09 AM

            // a error occurs
            if(date1.before(date2))
            {
                return "True";
            }
            else
            {
                return "False";
            }
        } 
        catch (ParseException e) 
        {
        e.printStackTrace();

        }

how to handle this?

NEO
  • 1,961
  • 8
  • 34
  • 53
  • what is DATE_FORMAT_yyyy_mm_dd_hh_mm_ss? can you provide definition? just curiosity, did you use mm for monts and minutes? – user902383 Feb 21 '13 at 09:20

2 Answers2

1

For Month in year Use M instead of m

Correct date format would be yyyy/MM/dd hh:mm:ss aaa. And If there is any additional space or new line then you must remove it other wise it will failed to parse your string to date, your should exact match with format .

I would suggest you to remove all space and new line character then parse it.

you can use format like - yyyy/MM/ddhh:mm:ssaaa where there is no space. And replaceAll your space and new Line with empty String.

Date date = new SimpleDateFormat("yyyy/MM/ddhh:mm:ssaaa").parse("2013/02/1407:00:00AM");

and you actual code could be like -

dateString = dateString.replaceAll("\\s","");
SimpleDateFormat("yyyy/MM/ddhh:mm:ssaaa").parse(dateString);
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
1

One of the simplest solutions is to strip all whitespace from the String version of the date before you parse it. Alter your date format to not include any spaces (yyyy/MM/ddhh:mm:ssaaa), and use this to parse the stripped string.

        final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/ddhh:mm:ssaaa");
        final String dateStr = "02/14/2013    07:00:00" +
                                "\n AM";
        Date failingDate = dateFormat.parse(dateStr);
        Date passingDate = dateFormat.parse(dateStr.replaceAll("\\s",""));
Community
  • 1
  • 1
Trisha
  • 3,891
  • 1
  • 25
  • 39