我想生成一个日期列表,但发现日期是错误的,从 - 25 * 24 * 60 * 60 * 1000 开始
我的本地日期是 2016 年 7 月 17 日。我得到了
2016-07-17 2016-07-16 2016-07-15 ... 2016-06-23 2016-08-11
I have no idea where the 2016-08-11
comes from. I broke down the 25 to 24 and -1 as below (xxx
and yyy
), and then I got the correct date 2016-06-22
.
Why does xxx
work but yyy
Doesn't?
Date xxx = new Date(new Date().getTime()-24 * 24 * 60 * 60 * 1000 -1 * 24 * 60 * 60 * 1000);
Date yyy = new Date(new Date().getTime()-25 * 24 * 60 * 60 * 1000);
这是我的代码:从 i=25 开始日期是错误的
for (int i=0; i<240;i++) {
Date dt = new Date(new Date().getTime() - i * 24 * 60 * 60 * 1000);
Log.e(TAG,Global.sdfDateTime19.format(dt));
}
最佳答案
您超出了 int
的范围。 i * 24 * 60 * 60 * 1000
产生一个 int
(然后从 getDate
的 long
中减去它).
i
为 24 时没问题,因为结果为 2,073,600,000,小于 int
的最大正值 2,147,483,647。但是,当您达到 i = 25
时,您将环绕(如果您不被限制为 int
,则该值将是 2,160,000,000,这太大了)。
通过将 i
声明为 long 或将 24 设为 long
使其成为 long
乘法:
Date dt = new Date(new Date().getTime() - i * 24L * 60 * 60 * 1000);
// ---------------------------------------------^
Why xxx works but yyy not work?
因为您已将乘法分解为两部分(为了清楚起见,我在其中添加了一个空格,因为 -1
否则看起来像负数而不是减法运算符后跟 1
):
Date xxx = new Date(new Date().getTime()-24 * 24 * 60 * 60 * 1000 - 1 * 24 * 60 * 60 * 1000);
// The first part -----------------------^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
// The second part ------------------------------------------------/
...而且您将它分解成的两个部分都没有溢出 int
的范围。
一般来说,我不建议以这种方式处理日期,尤其是因为并非所有的日子都正好是 24 小时(考虑进入和退出夏令时的日子)。我会使用一个库,让你在“白天”级别工作,例如 Java 8 java.time
东西,或 JodaTime,或类似的东西。
关于java - new Date(new Date().getTime()-25 * 24 * 60 * 60 * 1000) 得到了意外的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38420260/