java 如何为日历添加长值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3446731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add long value to calendar?
提问by Strudel
Calendar's add method in Java takes an integer as an input
Java中Calendar的add方法以整数作为输入
int secs = 3; cal.add(Calendar.SECOND, secs);
But what if the seconds are Long type.
但是如果秒是 Long 类型呢?
long secs = 3
long secs = 3
There's quite a few possibilities like adding the seconds iterative, but what are the other options?
有很多可能性,比如添加秒迭代,但其他选项是什么?
回答by Andreas Dolk
If the value stored in long secis less or equal then Integer.MAX_VALUEyou can cast to int:
如果存储的值long sec小于或等于,则Integer.MAX_VALUE可以转换为int:
cal.add(Calendar.SECOND, (int) sec));
If the value is less or equal Long.MAX_VALUE / 1000then you can convert the seconds to milliseconds and use a different approach:
如果该值小于或等于,Long.MAX_VALUE / 1000那么您可以将秒转换为毫秒并使用不同的方法:
cal.setTimeInMillis(cal.getTimeInMillis() + (sec*1000));
回答by jvdneste
回答by Oren Shalev
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.
例如,将秒数除以 86400 转换为天数,然后加上天数和剩余的秒数。您需要巧妙地做到这一点,因为即使除以 86400 后,结果也可能大于 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.
另一种方法是使用 getMillisOf() 将日历转换为毫秒,添加您想要的值,然后使用 setTimeInMillis() 设置它。这更简单,犯错的风险很小,只需记住将秒转换为毫秒。
回答by InsertNickHere
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.
Afaik 日历在内部将值存储为整数,因此无法将 long 放入其中。如果我错了,请纠正我,但这是我从Java 日历中读出的内容。您应该将秒数转换为几天左右以获得您想要的结果。
回答by Mohammad Roshani
if your number is big, one idea is that you do it in TOW TIME add()
如果你的数字很大,一个想法是你在 TOW TIME add()
MaxInt: 2147483647
MaxLong: 9223372036854775807
therefore
所以
cal.add(Calendar.SECOND, secs / 1000000000);
cal.add(Calendar.SECOND, secs % 1000000000);

