Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set an expiration date in java

Tags:

java

date

I am trying to write some code to correctly set an expiration date given a certain date.

For instance this is what i have.

    Date lastSignupDate = m.getLastSignupDate();
    long expirationDate = 0;
    long milliseconds_in_half_year = 15778463000L;
    expirationDate = lastSignupDate.getTime() + milliseconds_in_half_year; 
    Date newDate = new Date(expirationDate);

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?

like image 636
thunderousNinja Avatar asked Dec 28 '25 16:12

thunderousNinja


2 Answers

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

    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);
like image 119
planetjones Avatar answered Dec 30 '25 05:12

planetjones


Here's a simple suggestion using joda-time:

DateTime dt = new DateTime(lastSignupDate);
dt = dt.plusDays(DateTimeConstants.MILLIS_PER_DAY * 365 / 2);
// you can also use dt.plusDays(364 / 2);

You can also use a Calendar:

Calendar c = Calendar.getInstance();
c.setTime(lastSignupDate);
c.add(Calendar.MILLISECOND, MILLIS_PER_DAY * 365 / 2);
// or c.add(Calendar.DAY_OF_YEAR, 364 / 2);
like image 20
Bozho Avatar answered Dec 30 '25 04:12

Bozho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!