Search code examples
androidandroid-activitysimpledateformatdate-parsingandroid-date

Exception on Date parsing android


I am using a function to take out the difference between a given date and current date. At all the places, that function is working just fine but at one place, it is throwing the unparseable date exception.

Below is the function that I use:

public boolean timeDiff24hrs(String alarmTime) {

    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy'T'HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date date = new Date();
    String s = sdf.format(date);
    String alarmDateStr="";
    try {
        Date alarmDate=sdf.parse(alarmTime);
        alarmDateStr=sdf.format(alarmDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    int diff = diffOf2Days(alarmDateStr, s);

    if (diff > 1439) {
        return true;
    }
    return false;
}

Here I get the exception trying to execute the try block.

The alarmDate that I pass into the function is : 1/31/2018 8:58:12 AM +00:00

Can someone please explain.


Solution

  • Your date format MM/dd/yyyy'T'HH:mm:ss which your using is incorrect 1/31/2018 8:58:12 AM +00:00 and return different value from expected.

    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy'T'HH:mm:ss");
    

    return 1/31/2018T8:58:12

    And you are trying to pass below

    1/31/2018 8:58:12 AM +00:00