【发布时间】:2010-11-23 06:51:38
【问题描述】:
如何找到给定Locale 的DateFormat?
【问题讨论】:
-
仅供参考,麻烦的旧日期时间类,如
DateFormat现在是 legacy,被 java.time 类取代。见Tutorial by Oracle。
如何找到给定Locale 的DateFormat?
【问题讨论】:
DateFormat 现在是 legacy,被 java.time 类取代。见Tutorial by Oracle。
DateFormat.getDateInstance(int,Locale)
例如:
import static java.text.DateFormat.*;
DateFormat f = getDateInstance(SHORT, Locale.ENGLISH);
那么就可以用这个对象来格式化Dates:
String d = f.format(new Date());
如果您真的想知道底层模式(例如yyyy-MMM-dd),那么您将得到一个SimpleDateFormat 对象:
SimpleDateFormat sf = (SimpleDateFormat) f;
String p1 = sf.toPattern();
String p2 = sf.toLocalizedPattern();
【讨论】:
SimpleDateFormat
java.text.SimpleDateFormat 之类的麻烦的旧日期时间类现在是legacy,被java.time 类所取代。见Tutorial by Oracle。
DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH );
原来的日期时间类现在是遗留的,并已被 java.time 类取代。
DateTimeFormatter 在生成表示日期时间值的字符串时,可以通过Locale 自动进行本地化。指定一个FormatStyle 来表示输出的长度(是否缩写)。
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL );
f = f.withLocale( Locale.CANADA_FRENCH );
获取当前时刻。请注意,Locale 和时区彼此无关。一个确定演示文稿,另一个调整为特定的wall-clock time。因此,您可以在新西兰的时区使用日语的Locale,或者在这种情况下,在印度的时区使用格式为魁北克人阅读的演示文稿。
ZoneId z = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = ZonedDateTime.now( z );
使用该本地化格式化程序对象生成一个字符串。
String output = zdt.format( f );
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
从哪里获得 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如Interval、YearWeek、YearQuarter 和more。
【讨论】: