java 1000 * 60 * 60 * 24 * 30 结果为负数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17221254/
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
1000 * 60 * 60 * 24 * 30 results in a negative number
提问by NoobDev954
I'm attempting to calculate 30 days by multiplying milliseconds however the result continually ends up being a negative number for the value of days_30 and I'm not sure why.
我试图通过乘以毫秒来计算 30 天,但是结果不断地最终成为 days_30 值的负数,我不知道为什么。
Any suggestions are greatly appreciated!
任何建议都非常感谢!
CODE SNIPPET:
代码片段:
// check to ensure proper time has elapsed
SharedPreferences pref = getApplicationContext()
.getSharedPreferences("DataCountService", 0);
long days_30 = 1000 * 60 * 60 * 24 * 30;
long oldTime = pref.getLong("smstimestamp", 0);
long newTime = System.currentTimeMillis();
if(newTime - oldTime >= days_30){
days_30 value results in: -1702967296
days_30 值导致:-1702967296
P.S.
聚苯乙烯
double days_30 = 1000 * 60 * 60 * 24 * 30;
double oldTime = pref.getLong("smstimestamp", 0);
double newTime = System.currentTimeMillis();
if(newTime - oldTime >= days_30){
Results in a smaller - but still negative number. -1.702967296E9
结果是一个较小的 - 但仍然是负数。-1.702967296E9
回答by rgettman
You are multiplying ints
together, and overflow occurs because the maximum integer is 2^31 - 1
. Only after the multiplications does it get converted to a long
. Cast the first number as a long
.
您正在相乘ints
,并且会发生溢出,因为最大整数为2^31 - 1
。只有在乘法之后它才会被转换为 a long
。将第一个数字转换为long
.
long days_30 = (long) 1000 * 60 * 60 * 24 * 30;
or use a long
literal:
或使用long
文字:
long days_30 = 1000L * 60 * 60 * 24 * 30;
That will force long
math operations from the start.
这long
将从一开始就强制进行数学运算。
回答by ZhongYu
long days_30 = 1L * 1000 * 60 * 60 * 24 * 30;
回答by Guillaume Darmont
Just change your multiplication to long days_30 = 1000L * 60 * 60 * 24 * 30;
只需将乘法更改为 long days_30 = 1000L * 60 * 60 * 24 * 30;
回答by But I'm Not A Wrapper Class
Java has limitations when it comes to primitive data types. If your long or double are too big, then it will overflow into a negative number. Try using the BigInteger class for storing larger numbers.
Java 在原始数据类型方面有局限性。如果您的 long 或 double 太大,那么它将溢出为负数。尝试使用 BigInteger 类来存储更大的数字。
Check this out:
看一下这个:
How does Java handle integer underflows and overflows and how would you check for it?