I have a date of type java.util.Date
I want to subtract three months from it.
Not finding a lot of joy in the API.
You can use Apache Commons Lang3 DateUtils addMonths function.
static Date addMonths(Date date, int amount)
Adds a number of months to a date returning a new object. The original Date is unchanged. The amount to add, may be negative, so you can go 3 months back.
String startDate="15/10/1987";
Date date = new SimpleDateFormat("dd/MM/yyyy").parse(startDate);
String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
LocalDate today = LocalDate.parse(formattedDate);
String endDate=today.minusMonths(3).toString();
public static Date getDateMonthsAgo(int numOfMonthsAgo)
{
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.MONTH, -1 * numOfMonthsAgo);
return c.getTime();
}
will return the date X months in the past. Similarily, here's a function that returns the date X days in the past.
public static Date getDateDaysAgo(int numOfDaysAgo)
{
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DAY_OF_YEAR, -1 * numOfDaysAgo);
return c.getTime();
}
You want today - 3 Month formatted as dd MMMM yyyy
SimpleDateFormat format = new SimpleDateFormat("dd MMMM yyyy");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.MONTH, -3);
Date d = c.getTime();
String res = format.format(d);
System.out.println(res);
So this code can do the job ;)
I always recommend Joda for this sort of stuff. It has a much nicer API, and doesn't suffer from threading issues that the standard Java date/time has (e.g. issues with SimpleDateFormat
, or general mutability).
e.g.
DateTime result = dt.minusMonths(3);
You can use
Date d1 = new Date()
d1.setMonth(d1.month-3)
Hope this helps