Java MessageFormat和LocalDate
我正在使用Java MessageFormat和LocalDate,java,Java,我正在使用 MessageFormat.format("Hello {0}", "World")); 现在我想使用LocalDate或LocalDateTime作为参数,但据我所知MessageFormat.format不支持java.time 所以我必须使用 MessageFormat.format("Today is {0,date}", Date.from(LocalDate.now().atSta
MessageFormat.format("Hello {0}", "World"));
现在我想使用LocalDate
或LocalDateTime
作为参数,但据我所知MessageFormat.format
不支持java.time
所以我必须使用
MessageFormat.format("Today is {0,date}",
Date.from(LocalDate.now().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()));
这太可怕了
有没有更好的方法将MessageFormat
与java.time
结合使用?或者,有没有更好的解决方案来替换考虑区域设置配置的文本中的占位符
更新
我知道如何格式化LocalDate和LocalDateTime,但我需要格式化各种类型的消息
范例
MessageFormat.format("Today is {0,date} {1,number} {2}", aDate, aNumber, aString);
用java.time
类型替换MessageFormat
的位置在哪里?为此打开了一个窗口,该窗口被解析为“不会修复”。原因是:
MessageFormat
设计用于java.text.Format
类,因此它使用DateFormat
/SimpleDateFormat
格式化日期/时间。为java.time.format.DateTimeFormatter
提供对java.time
类型(temporalAccessor
)的格式支持可能会使MessageFormat
API复杂化。始终建议使用java.util.Formatter
,它提供对java.time
类型格式化的支持
因此,您应该使用:
这适用于任何类型的
TemporalAccessor
我终于在MessageFormat
中找到了一个关于支持java.time
的错误报告
在解决此问题之前,我将使用建议的解决方法,并将
LocalDate
等转换为java.util.Date
LocalDate支持使用DateTimeFormatter()格式化自己。SimonMartinelli我不是建议使用DateTimeFormatter
的人。这是评论中的R先生。我对答案进行了编辑,以显示如何在消息中设置数字格式。ISO 8601格式是否让您认为它是DateTimeFormatter
?我把它改成另一种格式。问题是%TD不考虑这个区域。我得到的是03/30/21,而不是30.03。2021@SimonMartinelli啊,您希望整个格式对区域设置敏感<代码>格式化程序仅支持区分区域设置的月份名称、星期几和am/pm。但是从bug报告来看,MessageFormat
似乎不支持java.time
:(现在你明白我的问题了:-)你知道如何解决我的需求吗?
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
int someNumber = 10;
String someString = "Hello";
formatter.format("Today is %tD and someNumber is %d %s", LocalDate.now(), someNumber, someString);
System.out.println(sb);
// prints "Today is 03/30/21 and someNumber is 10 Hello"