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?
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.
Calendar 's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time: Calendar rightNow = Calendar.
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.
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));
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With