时间戳增加了额外的天数

时间:2016-03-21 15:15:07

标签: java android time

我以毫秒为单位得到当前时间,如

(System.currentTimeMillis() / 1000)
我在第一行中使用它:

foodObj.setValue("expires",(System.currentTimeMillis() / 1000)+ONE_WEEK+"");

使用static ints添加一到两周

public static int TWO_WEEKS = 1209600000;
public static int ONE_WEEK = 604800000;
public static int ONE_DAY = 86400000;

当我尝试稍后将其变为几天时,它会提前16或17天(如果它计算一天中的毫秒数,则为idk)

//keysValues.get("expires") contains the timestamp
Long exp= Long.parseLong(keysValues.get("expires"));
long days=TimeUnit.MILLISECONDS.toDays(exp)-16;//otherwise this is 23

为什么时间不一致?它是Long或String转换的东西吗?

1 个答案:

答案 0 :(得分:3)

System.currentTimeMillis() / 1000,您获得,而不是毫秒。因此,为了使代码正常工作,您应该使用适当的常量:

public static final int ONE_DAY = 24 * 60 * 60;   // 86400, not 86.4M
public static final int ONE_WEEK = ONE_DAY * 7;
public static final int TWO_WEEKS = ONE_WEEK * 2;

// ...
long days = TimeUnit.SECONDS.toDays(exp)

或不除以1000。

BTW,这不能处理可能的夏令时变化,但我相信它在这里不是那么重要。

相关问题