问题
两种计算时间戳的结果不一样。
int days = 30;
Instant now = Instant.now();
long timestamp_cur = now.toEpochMilli();
long nowPre = timestamp_cur - 1000 * 60 * 60 * 24 * days;
Instant threeDaysAgo = now.minus(days, ChronoUnit.DAYS);
long nowPre2 = threeDaysAgo.toEpochMilli();
System.out.println(String.format("nowPre: %d, nowPre2: %d, minus:%s", nowPre, nowPre2, nowPre-nowPre2));
当days=10,20时是一致的, 但当days=30时有差异。
原因
int 最大值:2147483647 (231-1), 当days=30时结果时2592000000, 超过int最大值,导致越界。
改正
显性指定大数的类型
long nowPre = timestamp_cur - 1000L * 60 * 60 * 24 * days;