2012-05-24 28 views
0

我有一個包含以下格式的時間的字符串:Java的Android的比較時間從字符串格式

"hh:mm tt" 

例如,你可以代表當前時間,「下午7時04分」

如何我可以將它與用戶時區中的當前時間進行比較,以查看此時間是否小於,等於或大於當前時間?

+0

我需要這樣做盡可能高效,因爲它將在服務中執行。 – zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz

+0

如果您只有7:04 PM而不是偏移量,您希望如何將其與用戶本地時區中的偏移時間進行比較?或者你的時間是基於特定的偏移? –

+0

它們基於特定的偏移量。 – zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz

回答

3

您可以將String轉換爲Date

String pattern = "<yourPattern>"; 
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); 
try { 
Date one = dateFormat.parse(<yourDate>); 
Date two = dateFormat.parse(<yourDate>); 

} 
catch (ParseException e) {} 

這是實現可比接口,這樣你應該能夠將它們與比較compareTo()


編輯: 我忘了,但你知道,但只可以肯定的compareTo返回-1,1或0 so one.compareTo(two)當第一次在第二秒之前返回-1時

3

以下代碼闡述了@ Sajmon的答案。

public static void main(String[] args) throws ParseException { 
    String currentTimeStr = "7:04 PM"; 

    Date userDate = new Date(); 
    String userDateWithoutTime = new SimpleDateFormat("yyyyMMdd").format(userDate); 

    String currentDateStr = userDateWithoutTime + " " + currentTimeStr; 
    Date currentDate = new SimpleDateFormat("yyyyMMdd h:mm a").parse(currentDateStr); 

    if (userDate.compareTo(currentDate) >= 0) { 
     System.out.println(userDate + " is greater than or equal to " + currentDate); 
    } else { 
     System.out.println(userDate + " is less than " + currentDate); 
    } 
} 
+0

Eclipse說你必須用一個try catch塊包圍SimpleDateFormat.parse()。 – zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz

+0

是的,這是真的。在上面的代碼中,'main'方法拋出了'ParseException'。在你的代碼中,就像在@ Sajmon的答案中一樣,我希望你會用try-catch塊來包圍'parse'。 – creemama