Can not find the number of days between two dates when the date format is dd-MMM-yyyy

advertisements

I'm using the following code to parse two dates of type 23-May-2016 and 25-May-2017 then I'm trying to find the number days between both dates.

Following is the code that I'm using to do so,

SimpleDateFormat format1 = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MMM-yyyy");
Date validityDate = null;
Date nextDueDate = null;
try {
    validityDate = format1.parse(mValidity.getText().toString());
    nextDueDate = format2.parse(mDueDate.getText().toString());
    int validate = validate(validityDate, nextDueDate);
    Toast.makeText(getApplicationContext(),""+validate,Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
    Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_SHORT).show();
}

the validate method is as follows,

public static int validate(Date valid, Date nextDueDate) {
    return (int) ((nextDueDate.getTime() - valid.getTime()) / (1000 * 60 * 60 * 24l));
}

When I'm trying to do so, I'm getting unable to parse at index offset 6. How can I sort this out?


you can try to use this code sample to change your SimpleDateFormat constructor call with the Locale specific version to make month string value (like "May") be parsable :

SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
Date validityDate = null;
Date nextDueDate = null;
try {
   validityDate = sdf.parse(mValidity.getText().toString());//string value like "25-May-2016"
   nextDueDate = sdf.parse(mDueDate.getText().toString());
   int validate = validate(validityDate, nextDueDate);
   Toast.makeText(getApplicationContext(),""+validate,Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
   Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_SHORT).show();
}

also it is not necessary to create two identical SimpleDateFormat instances in your case