开发者

How to add long value to calendar?

开发者 https://www.devze.com 2023-01-10 18:13 出处:网络
Calendar\'s add method in Java takes an integer as an input int secs = 3; cal.add(Calendar.SECOND, secs);

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 ar开发者_如何学JAVAe the other options?


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.


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.


if your number is big, one idea is that you do it in TOW TIME add()

MaxInt:  2147483647
MaxLong: 9223372036854775807

therefore

cal.add(Calendar.SECOND, secs / 1000000000);
cal.add(Calendar.SECOND, secs % 1000000000);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号