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?
SimpleDateFormat,DateandGregorianCalendar. Those classes are poorly designed and long outdated, the first in particular notoriously troublesome. Instead just useLocalDatefrom java.time, the modern Java date and time API.GregorianCalendarfor 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.