javadate

Finding date before given number of months from a given date


I have a date say for e.g. current date which is 19/04/2013

And I have number of months given say for e.g. 10

I want to find out the date falling before 10 months from 19/04/2013.

How to achieve it in Java?

For example, if I want to find out date before a week, I can achieve as below:

Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date newDate = calendar.getTime();

But how to find the same for months ?


Solution

  • Well, you could do something similar to your example:

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(myDate);
    calendar.add(Calendar.MONTH, -10);
    Date newDate = calendar.getTime();
    

    It'll set newDate to a date 10 months before myDate.