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
老班(Date
,Calendar
和SimpleDateFormat
)有lots of problems和design 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。
我找到了錯誤,如果我使用J7三星不工作的第一個代碼,如果我想工作必須設置此行 timeComeFromServer = timeComeFromServer.replaceAll(「PM」,「pm」)。replaceAll 「AM」,「am」); 但其他設備工作沒有任何replaye – ahmad