2017-08-13 311 views
5

我有一個問題在轉換時間來自服務器,我想將其轉換爲24小時。我使用下面的代碼:轉換字符串在12(下午/上午)小時上午下午時間到24小時時間android

String timeComeFromServer = "3:30 PM"; 

SimpleDateFormat date12Format = new SimpleDateFormat("hh:mm a"); 

SimpleDateFormat date24Format = new SimpleDateFormat("HH:mm"); 
try { 
    ((TextView)findViewById(R.id.ahmad)).setText(date24Format.format(date12Format.parse(timeComeFromServer))); 
} catch (ParseException e) { 
    e.printStackTrace(); 
} 

有錯誤:

Method threw 'java.text.ParseException' exception.)

詳細的錯誤消息:

Unparseable date: "3:30 PM" (at offset 5)

但是如果我更換PMp.m.它工作沒有任何像這樣的問題:

timeComeFromServer = timeComeFromServer.replaceAll("PM", "p.m.").replaceAll("AM", "a.m."); 

任何人都可以告訴我哪種方法正確嗎?

+0

我找到了錯誤,如果我使用J7三星不工作的第一個代碼,如果我想工作必須設置此行 timeComeFromServer = timeComeFromServer.replaceAll(「PM」,「pm」)。replaceAll 「AM」,「am」); 但其他設備工作沒有任何replaye – ahmad

回答

1

SimpleDateFormat使用系統的默認語言環境(可以使用java.util.Locale類來檢查,調用Locale.getDefault())。此區域設置是特定於設備/環境的,因此您無法控制它,並且可能在每個設備中具有不同的結果。

某些語言環境可能對AM/PM字段具有不同的格式。例如:

Date d = new Date(); 
System.out.println(new SimpleDateFormat("a", new Locale("es", "US")).format(d)); 
System.out.println(new SimpleDateFormat("a", Locale.ENGLISH).format(d)); 

輸出是:

p.m.
PM

爲了不取決於,你可以使用你的格式化Locale.ENGLISH,這樣你就不會依賴於系統/設備的默認配置:

String timeComeFromServer = "3:30 PM"; 
// use English Locale 
SimpleDateFormat date12Format = new SimpleDateFormat("hh:mm a", Locale.ENGLISH); 
SimpleDateFormat date24Format = new SimpleDateFormat("HH:mm"); 
System.out.println(date24Format.format(date12Format.parse(timeComeFromServer))); 

的輸出是:

15:30

第二個格式化程序不需要特定的區域設置,因爲它不處理特定於區域的信息。


新的Java日期/時間API

老班(DateCalendarSimpleDateFormat)有lots of problemsdesign issues,他們正在被新的API取代。

一個細節是,SimpleDateFormat總是與Date對象的作品,其中有完整的時間戳(自1970-01-01T00:00Z的毫秒數),而這兩類含蓄使用系統默認的時區behind the scenes,這可能會誤導你,會產生意外的和硬調試結果。但在這種特定情況下,您只需要時間字段(小時和分鐘),並且不需要使用時間戳值。新的API針對每種情況都有特定的類,更好,更不容易出錯。

在Android中,您可以使用ThreeTen Backport,它是Java 8新日期/時間類的一個很好的後端。爲了使它工作,你還需要ThreeTenABP(更多關於如何使用它here)。

您可以使用org.threeten.bp.format.DateTimeFormatter並解析輸入到org.threeten.bp.LocalTime

String timeComeFromServer = "3:30 PM"; 

DateTimeFormatter parser = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH); 
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm"); 

LocalTime time = LocalTime.parse(timeComeFromServer, parser); 
System.out.println(time.format(formatter)); 

輸出是:

15:30

對於這個特定的情況下,你也可以使用time.toString()來得到相同的結果。有關backport API的更多信息,請參閱javadoc

相關問題