Search code examples
javaandroiddatecalendaraddition

Android dateFormat.parse(date) I send 01/03/2021 it shows sun dec 27 00:00:00 GMT-05:00 2020


I am having a problem with this class where the string date is in format MM/dd/YYYY. The boolean is true to add a day and false to subtract a day.

Sending 01/03/2021 and on c.setTime(dateFormat.parse(date));, the value that it getting is Sun "Dec 27 00:00:00 GMT-05:00 2020". I don't understand what is the problem.

public static String dateDay(String date,boolean add){
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/YYYY");
    Calendar c = Calendar.getInstance();
    try {
        c.setTime(dateFormat.parse(date));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    if(add)
        c.add(Calendar.DAY_OF_YEAR,1);
    else
        c.add(Calendar.DAY_OF_YEAR,-1);
    dateFormat=new SimpleDateFormat("MM/dd/YYYY");
    Date newDate=new Date(c.getTimeInMillis());
    String resultDate=dateFormat.format(newDate);
    return resultDate;
}

Solution

  • SimpleDateFormat() uses lowercase yyyy for year not uppercase. Change the line

    dateFormat=new SimpleDateFormat("MM/dd/YYYY");
    

    to

    dateFormat=new SimpleDateFormat("MM/dd/yyyy");