2017-05-25 118 views
-1

我嘗試使用Joda時間庫來比較存儲時間字符串"hh:mm"格式與當前時間。我使用下面的代碼,但輸出是隨機的。它的輸出是不正確的。如何將HH:MM中的存儲時間與當前時間進行比較?

LocalTime now = LocalTime.now(); 
LocalTime limit; 
limit = LocalTime.parse(date); //date is any string data in format "hh:mm", e.g "14:30" 

if(now.isAfter(limit)){ 
    ans = date+"is Past or Present Time"; 
}else{ 
    ans = date+" is Future time"; 
} 
+0

你能不能給你提供的輸入,並得到了錯誤輸出的例子嗎? –

+0

我使用String作爲「HH:mm」格式的輸入,如「08:30」。我嘗試了不同的輸入,一些得到正確的答案,一些沒有。 – user3853770

+0

*你的意思是「輸出是隨機的」*,你期望輸出什麼? 'LocalTime.now()'會在代碼運行的機器中給你當前時間(使用默認的** TimeZone **)。你是否檢查過「現在」是否知道輸出是否錯誤? – 2017-05-25 11:24:32

回答

0

使用此代碼獲取當前日期:

Date date = new Date(); 
DateFormat format = new SimpleDateFormat("HHmm"); 
LocalTime now=LocalTime.parse(format.format(date)); 

然後嘗試進行比較,希望它會幫助你!因爲您正在使用LocalTime.now(),所以它也會有時間默認時區。

0

試試這可能對你有用。

public void DateComparision(String dateString) { 
    try { 

     //"yyyy-MM-dd" --> Here you can take your date format 

     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 

     // Get date object from given string 
     String givenDate = dateString; 
     Date date1 = null; 
     try { 
      date1 = sdf.parse(givenDate); 
     } catch (java.text.ParseException e) { 
      e.printStackTrace(); 
     } 

     // Get date object from current date 
     String currentDate = sdf.format(new Date()); 
     Date date2 = null; 

     try { 
      date2 = sdf.parse(currentDate); 
     } catch (java.text.ParseException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     if (date1.compareTo(date2) < 0) { 

      // Past date 

     } else if (date1.compareTo(date2) > 0) { 

      // Futer date 

     } else { 

      // Today date 

     } 

    } catch (ParseException e1) { 
     e1.printStackTrace(); 
    } 

} 
+0

謝謝ashish。這工作得很好。 – user3853770

+0

歡迎兄弟。 – ashish

相關問題