views:

203

answers:

3

Hi guys,

I am looking for the best way to add milliseconds to a Java Date when milliseconds is stored as a 'long'. Java calendar has an add function, but it only takes an 'int' as the amount.

This is one solution I am proposing...

Calendar now = Calendar.getInstance();
Calendar timeout = Calendar.getInstance();

timeout.setTime(token.getCreatedOn());
timeout.setTimeInMillis(timeout.getTimeInMillis() + token.getExpiresIn());

Any other suggestions?

+4  A: 

Your solution looks nearly fine to me, actually. I originally posted an answer going via Date, when I hadn't taken getTimeInMillis and setTimeInMillis into account properly.

However, you're calling setTime and then setTimeInMillis which seems somewhat redundant to me. Your code looks equivalent to this:

Calendar timeout = Calendar.getInstance();
timeout.setTimeInMillis(token.getCreatedOn().getTime() + token.getExpiresIn());

A generally nicer alternative would be to use Joda Time though :) It's generally a much nicer date/time API.

Jon Skeet
Ah, thanks, didn't notice that.
leaf dev
A: 

You can ao create a date with the current local date plus the number of miliseconds you need to add as Expire time

import java.util.Date;

long expiremilis = 60000l; //  1 minute
// Expires in one minute from now
Date expireDate = new Date(System.currentTimeMillis() + expiremilis);

Or the same with a calendar

long expiremilis = 60000l; // 1 minute
Calendar expireDate= Calendar.getInstance();
// Expires on one minute from now
expireDate.setTimeInMillis(System.currentTimeMillis() + expiremilis);

If you use an existing Date object you can do:

import java.util.Date;

long expiremilis = 60000l; // 1 minute
// Expires on one minute from the date object date
Date expireDate = new Date(myDate.getTime() + expiremilis);

And with an existing Calendar Object

long expiremilis = 60000l; // 1 minute
Calendar expireDate= Calendar.getInstance();
// Expires on one minute from the calendar date
expireDate.setTimeInMillis(myCalendar.getTimeInMillis() + expiremilis);
Dubas
A: 

Calendar is a fairly expensive Date object, and it functionality is not the best. If you want an all purpose Date object I suggest looking at JODE Time and it has a function which does what you want.

However, a simpler Java Date object is the Date class as @Dubas indicates.

Even simpler for the type of operation you are performing is to use a long. This is also much faster.

long timeoutMS = token.getCreatedOn() + token.getExpiresIn(); 

I use long (in GMT) for all my dates and only use Date for the presentation layer. ie. when you want to convert the date to Text.

Peter Lawrey