更新
OP 提到他想使用特定于语言环境的模式,但以英语输出。为此,DateTimeFormatterBuilder.getLocalizedDateTimePattern
可用于获取特定于语言环境的模式,然后可以在DateTimeFormatter
with中使用相同的模式Locale.ENGLISH
。
演示:
import java.time.Instant;
import java.time.ZoneId;
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.FormatStyle;
import java.time.format.TextStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ZoneId timezoneId = ZoneId.of("America/Los_Angeles");
Instant instant = Instant.now();
Locale userLocale = Locale.forLanguageTag("fr");
String pattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.LONG, null,
IsoChronology.INSTANCE, userLocale);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH);
System.out.println(instant.atZone(timezoneId).format(dtf) + " "
+ timezoneId.getDisplayName(TextStyle.SHORT_STANDALONE, Locale.ENGLISH));
}
}
输出:
18 January 2021 PT
用于测试:userLocale
将上述代码中的to值更改,Locale.US
输出将更改如下:
January 18, 2021 PT
原始答案
请注意Time4J 的作者 Meno Hochschild关于原始答案的以下评论:
基于样式的版本(您的前部分)和基于模式的版本(您的后部分)对于任何语言环境都不等效。
Java-10 之前:
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.FormatStyle;
import java.time.format.TextStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ZonedDateTime dateTime = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
Locale locale = Locale.forLanguageTag("fr");
DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder()
.appendLocalized(FormatStyle.LONG, null)
.appendLiteral(", ")
.appendZoneText(TextStyle.SHORT)
.toFormatter(locale);
String strLocalizedDate = dateTime.format(dateFormatter);
System.out.println(strLocalizedDate);
}
}
输出:
18 janvier 2021, PST
从 Java-10 开始:
你可以使用DateTimeFormatter#localizedBy(Locale locale)
如下图:
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ZonedDateTime dateTime = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
Locale locale = Locale.forLanguageTag("fr");
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd MMMM uuuu, z")
.localizedBy(locale);
String strLocalizedDate = dateTime.format(dateFormatter);
System.out.println(strLocalizedDate);
}
}
输出:
18 janvier 2021, PST