Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add long value to calendar?

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?

like image 432
Strudel Avatar asked Aug 10 '10 07:08

Strudel


People also ask

How do I add 30 days to a specific date in Java?

Adding Days to the given Date using Calendar class Add the given date to the calendar by using setTime() method of calendar class. Use the add() method of the calendar class to add days to the date. The add method() takes two parameter, i.e., calendar field and amount of time that needs to be added.

What does calendar getInstance() return?

Calendar 's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time: Calendar rightNow = Calendar.

How does calendar work java?

Calendar class in Java is an abstract class that provides methods for converting date between a specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It inherits Object class and implements the Comparable, Serializable, Cloneable interfaces.


3 Answers

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));
like image 145
Andreas Dolk Avatar answered Oct 31 '22 14:10

Andreas Dolk


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.

like image 44
jvdneste Avatar answered Oct 31 '22 13:10

jvdneste


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.

like image 2
Oren Shalev Avatar answered Oct 31 '22 13:10

Oren Shalev