0

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;
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • Which language is this written on? I can't tell. –  Jan 03 '21 at 18:47
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends. See if you either can use [desugaring](https://developer.android.com/studio/write/java8-support-table) or add [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project, in order to use java.time, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Jan 06 '21 at 04:26
  • @MarkGiraffe It’s Java (one of the more popular languages for Android development) (I have added the language tag). – Ole V.V. Jan 06 '21 at 04:27

1 Answers1

1

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

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

to

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