0

I have a string field which is returning a date value. I am trying to convert it into Date format and then subtract 30 days from it.

String extractDate; //2020-11-13 is the value
Date dateFormat= (Date) new SimpleDateFormat("yyyy/MM/dd").parse(onlyDate); //cannot parse Date error
GregorianCalendar cal = new GregorianCalendar();
cal.add(dateFormat, -30);

How to perform this operation in a more better way?

GKr297
  • 185
  • 2
  • 16
  • I recommend you don’t use `SimpleDateFormat`, `Date` and `GregorianCalendar`. Those classes are poorly designed and long outdated, the first in particular notoriously troublesome. Instead just use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Nov 13 '20 at 19:52
  • 1
    The good answer by Vlad L solves your problems. Apart from using the outdated classes and a couple of minor points two things went wrong in your code: (1) Using `GregorianCalendar` for subtracting days involves more steps than what you tried; your code does not compile. (2) Your date string and your format pattern string don’t match: one has hyphens between the numbers, the other’s got slashes. – Ole V.V. Nov 13 '20 at 19:55

1 Answers1

3

Date is being phased out, there are new classes you could use if you are OK with that (ie it is not compulsory to use Date). For example:

        String extractDate = "2020-11-13";
        LocalDate date = LocalDate.parse(extractDate);
        LocalDate newDate = date.minusDays(30);
        System.out.println(newDate);
Vlad L
  • 1,544
  • 3
  • 6
  • 20