Emmanuel
Emmanuel

Reputation: 3

How to add number of months to a specific date

I want to add a number of months to a specific date based on what that user selected. for instance adding 3 months to 15/05/2015. I tried something but its showing me the same date.

Code below:

Calendar aed = Calendar.getInstance();
int monthsToAdd = 0;
if (advertPostedDate.equals(1)) {
    monthsToAdd = 1;
}
if (advertPostedDate.equals(2)) {
    monthsToAdd = 2;
}
if (advertPostedDate.equals(3)) {
    monthsToAdd = 3;
}

aed.add(Calendar.MONTH, monthsToAdd);
Date advertED = aed.getTime();
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
String advertExpiryDate = df.format(advertED);

Upvotes: 0

Views: 74

Answers (2)

Shar1er80
Shar1er80

Reputation: 9041

Your code looks fine, with exception that I would use an if/else if structure instead of just the if structure. Are you sure advertPostedDate has a value of 1, 2, or 3? Because if it doesn't then 0 is being added to months.

public static void main(String[] args) {
    Integer advertPostedDate = 2;

    Calendar aed = Calendar.getInstance(); // 15-5-2015
    int monthsToAdd = 0;
    if (advertPostedDate.equals(1)) {
        monthsToAdd = 1;
    } else if (advertPostedDate.equals(2)) {
        monthsToAdd = 2;
    } else if (advertPostedDate.equals(3)) {
        monthsToAdd = 3;
    }

    aed.add(Calendar.MONTH, monthsToAdd);
    Date advertED = aed.getTime();
    DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
    String advertExpiryDate = df.format(advertED);

    System.out.println(advertExpiryDate);
}

Results:

15-07-2015

Upvotes: 1

Vasco Lameiras
Vasco Lameiras

Reputation: 364

I suggest that you use Joda-Time

DateTime dt = new DateTime(2015, 5, 15, 12, 0, 0, 0);
DateTime plusPeriod = dt.plusMonths(3);

Upvotes: 0

Related Questions