2012-12-20 35 views
1

我想計算兩次在android中的差異: 現在的日期和1356033600000之間的區別 - 從location.getTime()android:我如何計算時間跨度

= 2分鐘前

>戳我只需要幾分鐘! 我該怎麼辦?

我通過json獲取客戶端時間。 clienttime = 1356033600000

String clienttime = e.getString("clienttime"); 
long mTime = (System.currentTimeMillis() - Long.valueOf(clienttime).longValue())/(60 * 1000); 

回答

1

(System.currentTimeMillis的() - location.getTime())/(60 * 1000)

+0

我試着像這樣,但它不工作: 我通過JSON得到clienttime。我編輯我的帖子 – sarahsdev

+0

你的時鐘是否同步並使用相同的時區? –

0

這是一個代碼,用我自己的應用程序代碼段至極我':

    String oldDate = xmlResults[3]; //insert old dateTime in the following format: yyyy-MM-dd HH:mm:ss 
        int myValue = 15; //Check if difference is between 15 hours 

        // Date Time Format 
        SimpleDateFormat formatter = new SimpleDateFormat(
          "yyyy-MM-dd HH:mm:ss"); 

        // Convert Date to Calendar 
        Date xmlDate = formatter.parse(oldDate); 
        Calendar cal = Calendar.getInstance(); 
        cal.setTime(xmlDate); 

        Calendar today = Calendar.getInstance(); 

        // Check difference 
        long diff = today.getTimeInMillis() - cal.getTimeInMillis(); 

        long hours = diff/3600000; // 1000ms * 60sec * 60hours -> 
                // total hours 

        if (hours < myValue && hours >= 0) { 
         // Login is successful, return true 
         return true; 
        } else { 
         return false; 
        } 

您可以輕鬆更改代碼比較分鐘再予。

1

時間是在安卓/ Java的毫秒典型的計算,可以使用現有的常量來幫助你完成這個簡單的檢查:

//         now   minus   two minutes 
if(location.getTime() > System.currentTimeInMillis() - 2 * DateUtils.MINUTE_IN_MILLIS) { 
    // The location is less than two minutes old 
} 
else { 
    // The location is possibly stale 
} 

這是一種常見的檢查,當您使用LocationManager#getLastKnownLocation(),只要確保location在致電location.getTime()之前不爲空。