2017-03-06 184 views
-2

我從服務器獲取此格式的日期和時間dd.MM. HH:mm。我想獲得當前城市的日期和時間,不管我住在哪裏的格式相同,並檢查它是否少於20分鐘。我該怎麼做呢?Android比較時間

+0

我需要儘快:(的 – MagdHo0506

+0

可能的複製[Android的 - 比較兩個日期(http://stackoverflow.com/questions/33032762/android-compare -two-dates) –

+0

你有什麼試過的嗎?發佈一些相關的代碼並指出你遇到麻煩的地方? – Andrew

回答

0

我已經使用此代碼來獲得最小差異。 它還需要一年的日期。

public static int getDifferenceTimeInMin(String startDate, String endDate) 
{ 

     SimpleDateFormat simpleDateFormat = 
       new SimpleDateFormat(getString(R.string.common_dateTime_format)); 


     Date date2 = null; 
     Date date1 = null; 
     try { 
      date1 = simpleDateFormat.parse(startDate); 
      date2 = simpleDateFormat.parse(endDate); 
     } catch (ParseException e) { 
      e.printStackTrace(); 
     } 


     //milliseconds 
     long different = date1.getTime() - date2.getTime(); 

     //System.out.println("startDate : " + startDate); 
     //System.out.println("endDate : "+ endDate); 
     System.out.println("different : " + different); 

     long secondsInMilli = 1000; 
     long minutesInMilli = secondsInMilli * 60; 
     long hoursInMilli = minutesInMilli * 60; 
     long daysInMilli = hoursInMilli * 24; 

     long elapsedDays = different/daysInMilli; 
     different = different % daysInMilli; 

     long elapsedHours = different/hoursInMilli; 
     different = different % hoursInMilli; 

     long elapsedMinutes = different/minutesInMilli; 
     different = different % minutesInMilli; 

     long elapsedSeconds = different/secondsInMilli; 

     System.out.printf(
       "%d days, %d hours, %d minutes, %d seconds%n", 
       elapsedDays, 
       elapsedHours, elapsedMinutes, elapsedSeconds); 

     // int Hours = Integer.parseInt(String.valueOf(elapsedHours)); 

     return Integer.parseInt(String.valueOf(elapsedMinutes)); 

} 

希望這將有助於...