[Q#5922004][A#5922046] How to set an expiration date in java
https://stackoverflow.com/q/5922004
I am trying to write some code to correctly set an expiration date given a certain date. For instance this is what i have. However, say if i the sign up date is on 5/7/2011 the expiration date output i get is on 11/6/2011 which is not exactly half of a year from the given date. Is there an easier way to do this?
Answer
https://stackoverflow.com/a/5922046
I would use the Calendar class - the add method will do this kind of thing perfectly. http://download.oracle.com/javase/6/docs/api/java/util/Calendar.html
APIzation
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, 6);
java.util.Date expirationDate = cal.getTime();
System.err.println(expirationDate);
package com.stackoverflow.api;
import java.util.Calendar;
import java.util.Date;
public class Human5922046 {
public static Date setExpirationDate(
Date date,
int calendarField,
int amount
) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(calendarField, amount);
java.util.Date expirationDate = cal.getTime();
return expirationDate;
}
}
package com.stackoverflow.api;
import java.util.Calendar;
import java.util.Date;
/**
* How to set an expiration date in java
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/5922046">https://stackoverflow.com/a/5922046</a>
*/
public class APIzator5922046 {
public static void setDate() throws Exception {
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, 6);
java.util.Date expirationDate = cal.getTime();
System.err.println(expirationDate);
}
}