1

I have a date field that is being placed into a .csv and I need to subtract one day from each date. These dates are taken from one csv as a String variable, and placed into another as a String variable. These dates are all formatted as mm/dd/yyyy, and I need to subtract one day from each of these dates. I am looking for the best solution on how to do this.

For example I have a date as 7/28/2016 which I need to be taken to 7/27/2016.

All help is very appreciated, thanks in advance.

EDIT: I really appreciate all the answers so fast, really ended up separating this into steps like the first comment, I could have used the JodaTime answer but I just went other options that i was seeing around.

This is the code:

private String subtractDate(String date) {
        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        String returnValue = "";
        try {
            Date newDate = formatter.parse(date);
            Calendar cal = Calendar.getInstance();
            cal.setTime(newDate);
            cal.add(Calendar.DATE, -1);
            Date minusOne = cal.getTime();
            returnValue = formatter.format(minusOne);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnValue;
    }

This is working correctly now, again I really appreciate all the answers. I'm going to accept the first answer as I see it would work, but I just did not go that route.

Nicholas Pesa
  • 2,156
  • 2
  • 24
  • 45

1 Answers1

1
SimpleDateFormat dateFormat = new SimpleDateFormat("mm/dd/yyyy");

Date date = dateFormat.parse("Your date as String");

After that you can subtract the day using JodaTime.

DateTime dateTime = new DateTime(date);

dateTime.minusDays(1); `

  • I really like this, as it is explicit in what I want to do, and still may try this one out. Thanks for the help! – Nicholas Pesa Jul 25 '16 at 17:32
  • Oh no, don't use "mm" (minutes), use "MM" (months). And mixing `SimpleDateFormat` with Joda-Time is horrible. I would have expected Jodas own format engine to be suggested in this case. – Meno Hochschild Jul 26 '16 at 17:12