views:

71

answers:

4

Calendar's add method in Java takes an integer as an input

int secs = 3;
cal.add(Calendar.SECOND, secs);

But what if the seconds are Long type.

long secs = 3

There's quite a few possibilities like adding the seconds iterative, but what are the other options?

+5  A: 

If the seconds' long value is not too large to fit into an integer, cast.

long secs = 3;
cal.add(Calendar.SECOND, (int) secs);

But I would strongly advise you to use joda time instead of the java calendar API.

jvdneste
+1 for joda time.
InsertNickHere
A: 

Convert the seconds to, for example, days by dividing by 86400, then add days and the remaining seconds. You'll need to to this smartly, since even after dividing by 86400 the result may be larger than an int.

Another way is to convert the calendar to milliseconds with getMillisOf(), add the value you want, then set it with setTimeInMillis(). This is simpler and with very little risk of making a mistake, just remember to convert your seconds to milliseconds.

Oz
A: 

Afaik the calendar stores the values as ints internally, so there is no way to fit a long into it. Correct me if im wrong, but that is what i read out of Java calendar. You should convert your seconds to days or so to get what you want.

InsertNickHere
+1  A: 

If the value stored in long sec is less or equal then Integer.MAX_VALUE you can cast to int:

cal.add(Calendar.SECOND, (int) sec));

If the value is less or equal Long.MAX_VALUE / 1000 then you can convert the seconds to milliseconds and use a different approach:

cal.setTimeInMillis(cal.getTimeInMillis() + (sec*1000));
Andreas_D
I set the maximum allowed Date to be 'Long.MAX_VALUE / 1000' which is more than enough and used cal.setTimeInMillis(cal.getTimeInMillis() + (sec*1000));
Strudel