java.util.Date - Deleting three months from a date?

Viewed 101013

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.

11 Answers

Using Java 8 you can do it like this,

Date d = Date.from(LocalDate.now().minusMonths(3).atStartOfDay(ZoneId.systemDefault()).toInstant());

The LocalDate class has a lot of methods to help you make easy computations about dates like the above,

// Add 2 months
Date d = Date.from(LocalDate.now().plusMonths(2).atStartOfDay(ZoneId.systemDefault()).toInstant());
// Add 5 days
Date d = Date.from(LocalDate.now().plusDays(5).atStartOfDay(ZoneId.systemDefault()).toInstant());
// Minus 1 day and 1 year
Date d = Date.from(LocalDate.now().minusYears(1).minusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());

In order to compute time you can use the LocalDateTime class,

// Minus 1 year, minus 1 days, plus 1 hour
Date d = Date.from(LocalDateTime.now().minusYears(1).minusDays(1).plusHours(1).toLocalDate().atStartOfDay(ZoneId.systemDefault()).toInstant());
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 can use

Date d1 = new Date()
d1.setMonth(d1.month-3)

Hope this helps

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();
Related