实现说明
本地化格式按 Locale 渲染可以归结为类 InvoiceDate和函数 main。
for (Locale locale : new Locale[] {Locale.US, Locale.CHINA, Locale.GERMANY}) 反复执行,循环体之外没有别的重复。
使用要点
- 每一步打印都带着自己的标签:
FULL:。
常见问题
运行「本地化格式按 Locale 渲染」会打印什么?
运行文件本身,FULL: 这些前缀各对应一段演示逻辑。
核心语句
ZonedDateTime zoned = billed.atStartOfDay(java.time.ZoneId.of("Asia/Shanghai"));
DateTimeFormatter fmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(locale);
LocalDate billed = LocalDate.of(2026, 11, 23);
代码示例
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
public class InvoiceDate {
public static void main(String[] args) {
LocalDate billed = LocalDate.of(2026, 11, 23);
// 同一日期,同一 FormatStyle.MEDIUM,locale 决定具体模式与月名文本
for (Locale locale : new Locale[] {Locale.US, Locale.CHINA, Locale.GERMANY}) {
DateTimeFormatter fmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(locale);
System.out.println(locale + " -> " + billed.format(fmt));
}
// SHORT 紧凑、FULL/LONG 最完整,但 FULL/LONG 要求 temporal 带时区
ZonedDateTime zoned = billed.atStartOfDay(java.time.ZoneId.of("Asia/Shanghai"));
System.out.println("FULL: "
+ zoned.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL)
.withLocale(Locale.US)));
}
}