java - How to add number of months to a specific date -
i want add number of months specific date based on user selected. instance adding 3 months 15/05/2015. tried showing me 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);
your code looks fine, exception use if/else if
structure instead of if
structure. sure advertposteddate has value of 1, 2, or 3? because if doesn't 0 being added 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
Comments
Post a Comment