,而不是與SimpleDateFormat
直接合作(在這種老的API有lots of problems和design issues),你可以使用ThreeTen Backport,對Java 8的新的日期/時間類有很大反向移植。要在Android中使用它,您還需要ThreeTenABP(有關如何使用它的更多信息,請參閱here)。
要使用的主要類是org.threeten.bp.ZonedDateTime
(可以解析日期/時間輸入)和org.threeten.bp.format.DateTimeFormatter
(用於控制輸出格式)。
如果你正在閱讀這個領域(2017-06-22T16:18:04Z
)爲String
,你可以創建一個ZonedDateTime
這樣的:
ZonedDateTime z = ZonedDateTime.parse("2017-06-22T16:18:04Z");
如果你已經有了一個java.util.Date
對象,你可以使用org.threeten.bp.DateTimeUtils
與org.threeten.bp.ZoneOffset
轉換它:
Date date = // get java.util.Date
ZonedDateTime z = DateTimeUtils.toInstant(date).atZone(ZoneOffset.UTC);
在結束時,ZonedDateTime
對象將具有webPublicationDate
值。
要獲得不同的輸出格式,只需爲每種格式創建一個DateTimeFormatter
即可。在下面的例子中,我也用java.util.Locale
類,以確保月份名稱都是英文:
// for Mar 3, 1984
DateTimeFormatter f1 = DateTimeFormatter.ofPattern("MMM d, yyyy", Locale.ENGLISH);
// for 4:40 PM
DateTimeFormatter f2 = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
// for 16:18
DateTimeFormatter f3 = DateTimeFormatter.ofPattern("HH:mm", Locale.ENGLISH);
System.out.println(f1.format(z)); // Jun 22, 2017
System.out.println(f2.format(z)); // 4:18 PM
System.out.println(f3.format(z)); // 16:18
輸出是:
2017年6月22日
下午4時18
16 :18
請注意,它使用UTC時區(Z
在2017-06-22T16:18:04Z
)。如果你想顯示在另一個時區的日期和時間,只需使用org.threeten.bp.ZoneId
類:
System.out.println(f3.format(z.withZoneSameInstant(ZoneId.of("Europe/London")))); // 17:18
輸出是17:18
(becase的倫敦夏季時間了)。
請注意,API使用IANA timezones names(始終格式爲Continent/City
,如America/Sao_Paulo
或Europe/Berlin
)。 避免使用3字母縮寫(如CST
或),因爲它們是ambiguous and not standard。要找到更適合每個地區的時區,請使用ZoneId.getAvailableZoneIds()
方法,並檢查哪一個最適合您的用例。
如果你不希望其他依賴添加到您的項目並使用SimpleDateFormat
,你做同樣的事情(創建一個解析器和3輸出格式化,並使用英語語言環境)。另外不要忘記設置時區 - 我在下面使用UTC,但您可以將其更改爲您想要的任何時區。
// parse date
String dateInString = "2017-06-22T16:18:04Z";
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date date = parser.parse(dateInString);
// create output formatters (set timezone to UTC)
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat s1 = new SimpleDateFormat("MMM d, yyyy", Locale.ENGLISH);
s1.setTimeZone(utc);
SimpleDateFormat s2 = new SimpleDateFormat("h:mm a", Locale.ENGLISH);
s2.setTimeZone(utc);
SimpleDateFormat s3 = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
s3.setTimeZone(utc);
System.out.println(s1.format(date));
System.out.println(s2.format(date));
System.out.println(s3.format(date));
的輸出將是相同的:
2017年6月22日
下午4點18
16:18
而且重複的:https://開頭計算器。 com/q/2201925和https://stackoverflow.com/q/31090946 –