TL;博士
String output = LocalDate.now(ZoneId.of("America/Montreal")).format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).withLocale(Locale.CANADA_FRENCH));
詳細
的問題和其他的答案是使用舊的過時的類(SimpleDateFormat的,日期,日曆等)。
改爲使用內置於Java 8及更高版本中的java.time框架。見Oracle Tutorial。許多java.time功能被移植到ThreeTen-Backport中的Java中,並進一步適用於Android的ThreeTenABP。
LocalDate
類表示沒有時間和無時區的僅有日期的值。
要獲取當前日期,您需要一個時區。對於任何特定時刻,全球各地按時區排列的日期。
ZoneId zoneId = ZoneId.of("America/Montreal");
LocalDate today = LocalDate.now(zoneId);
要獲得標準ISO 8601格式YYYY-MM-DD,請撥打toString
。
String output = today.toString();
到所述串的localize the format and content產生表示日期值,使用DateTimeFormatter
與FormatStyle
以確定長度(完全,長,中,短整數)。
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
指定一個特定的Locale
而不是您的JVM的當前默認值。
Locale locale = Locale.CANADA_FRENCH;
formatter = formatter.withLocale(locale);
String output = today.format(formatter);
就是這樣,很簡單。只需根據需要定義Locale
,如Locale.CANADA
,Locale.CANADA_FRENCH
,Locale.GERMANY
,Locale.KOREA
,或者使用傳遞人類語言的各種構造函數,以及可選的國家和變體。