如何给日历添加长值?
Java中Calendar的add方法接受一个整数作为输入
int secs = 3; cal.add(Calendar.SECOND, secs);
但是如果秒是Long类型怎么办?
long secs = 3
有很多可能性,例如添加秒迭代,但其他选项是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果存储在
long sec
中的值小于或等于Integer.MAX_VALUE
,您可以转换为int
:如果该值小于或等于< code>Long.MAX_VALUE / 1000 那么您可以将秒转换为毫秒并使用不同的方法:
If the value stored in
long sec
is less or equal thenInteger.MAX_VALUE
you can cast toint
:If the value is less or equal
Long.MAX_VALUE / 1000
then you can convert the seconds to milliseconds and use a different approach:如果秒的长整型值不太大而无法放入整数,则强制转换。
但我强烈建议您使用 joda 时间 而不是 java 日历API。
If the seconds' long value is not too large to fit into an integer, cast.
But I would strongly advise you to use joda time instead of the java calendar API.
例如,通过除以 86400 将秒转换为天,然后添加天和剩余的秒。您需要巧妙地处理这一点,因为即使除以 86400 之后,结果也可能大于 int。
另一种方法是使用 getMillisOf() 将日历转换为毫秒,添加所需的值,然后使用 setTimeInMillis() 设置它。这更简单,犯错误的风险很小,只需记住将秒转换为毫秒即可。
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.
据我所知,日历在内部将值存储为整数,因此无法将长整型放入其中。如果我错了,请纠正我,但这就是我从 Java 日历。您应该将几秒钟转换为几天左右才能得到您想要的东西。
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.
如果你的数量很大,
一个想法是你在 TOW TIME add() 中完成它,
因此
if your number is big,
one idea is that you do it in TOW TIME add()
therefore