如何获取本地化的日期模式字符串?
使用 DateFormat,即我可以将当前日期格式化为短本地化日期,如下所示:
It is quite easy to format and parse Java Date (or Calendar) classes using instance of DateFormat, i.e. I could format current date into short localize date like this:
DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
String today = formatter.format(new Date());
我的问题是:我需要获取这个本地化的模式字符串(即像 "MM/dd/yy"
之类的东西).这应该是一项微不足道的任务,但我就是找不到提供者...
My problem is: I need to obtain this localized pattern string (i.e. something like "MM/dd/yy"
). This should be a trivial task, but I just couldn't find the provider...
推荐答案
For SimpleDateFormat,你调用 toLocalizedPattern()
对于 Java 8 用户:
For Java 8 users:
Java 8 日期时间 API 类似于 Joda-time.为了获得本地化模式,我们可以使用类DateTimeFormatter
The Java 8 Date Time API is similar to Joda-time. To gain a localized pattern we can use class DateTimeFormatter
DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
请注意,当您在 LocalDate 上调用 toString() 时,您将获得 ISO-8601 格式的日期
Note that when you call toString() on LocalDate, you will get date in format ISO-8601
请注意,Java 8 中的日期时间 API 受到 Joda Time 的启发,大多数解决方案都可以基于与时间相关的问题.
Note that Date Time API in Java 8 is inspired by Joda Time and most solution can be based on questions related to time.
相关文章