在 Java 中为当前时间添加一个大时间戳 [英] Adding a large timestamp to the current time in Java
问题描述
我正在开发一个支持 Google 两步验证的应用程序.此应用程序还支持信任此设备 30 天"的功能.
I am working on an application that supports Google 2-step verification. This application also supports a feature to 'trust this device for 30 days'.
我使用数据库来保存所有这些信息,例如 IP 地址和过期时间.现在,当我填写时间戳 System.currentTimeMillis() + 30 * 24 * 60 * 60 * 1000
以将当前时间添加 30 天时,它会在数据库中插入一个早于当前时间的时间戳.
I use a database to save all this information such as IP-addresses and expire times. Now when I fill in the timestamp System.currentTimeMillis() + 30 * 24 * 60 * 60 * 1000
to add 30 days to the current time, it inserts a timestamp earlier than the current time into the database.
例如:当前时间 = 1483223733000 (2016-31-12 11:36 PM UTC+1)
.现在,当我添加 30 天(即 2592000000
毫秒)时,它的日期类似于 1481520984841 (2016-12-12 6:36 AM UTC+1)
不是提前 30 天,而是提前 19 天.
For example: the current time = 1483223733000 (2016-31-12 11:36 PM UTC+1)
.
Now when I add 30 days (which is 2592000000
milliseconds, it comes to a date similar to 1481520984841 (2016-12-12 6:36 AM UTC+1)
which is not 30 days ahead, but rather about 19 days back in time.
推荐答案
这个问题与 32 位整数溢出有关.由于整数的最大值是 2147483647
,以毫秒为单位的 30 天对于整数来说太大了,并且会导致像 -1702967296
这样的整数(大约是 -19以毫秒为单位的天数.)
This problem had to do with a 32-bit integer overflow. Since the maximum value for an integer is 2147483647
, 30 days in milliseconds would be too large for an integer and would result in an integer like -1702967296
(Which is about -19 days in milliseconds.)
为了解决这个问题,我使用了 long
而不是 int
.所以现在我这样做:System.currentTimeMillis() + 30L * 24 * 60 * 60 * 1000;
To solve this problem, I use a long
instead of an int
. So now I do:
System.currentTimeMillis() + 30L * 24 * 60 * 60 * 1000;
这篇关于在 Java 中为当前时间添加一个大时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!