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?

2
  • 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. Commented Nov 13, 2020 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. Commented Nov 13, 2020 at 19:55

1 Answer 1

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); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.