2016-03-21 102 views
0

我得到以毫秒爲單位的當前時間像時間戳增加了額外的天

(System.currentTimeMillis()/1000) 

符合我使用它:

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

,並添加一或兩週使用靜態整數

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

當我嘗試後來把它變成幾天的時候,我認爲它是16或17天(如果它將一天中的毫秒數表示爲一天),那麼它會提前

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

爲什麼時間不一致?這是一個長或字符串轉換的東西?

+0

如果您希望獲得7作爲輸出,那麼請不要使用System.currentTimeMillis,只需在一週內將您的常量保持爲幾毫秒並稍後恢復。 –

回答

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劃分,這不處理可能出現的夏令時鐘的變化,但我相信它在這裏並不重要。