tl;博士
让 JSR 310 的现代java.time类自动生成本地化文本,而不是硬编码 12 小时制和 AM/PM。
LocalTime // Represent a time-of-day, without date, without time zone or offset-from-UTC.
.now( // Capture the current time-of-day as seen in a particular time zone.
ZoneId.of( "Africa/Casablanca" )
) // Returns a `LocalTime` object.
.format( // Generate text representing the value in our `LocalTime` object.
DateTimeFormatter // Class responsible for generating text representing the value of a java.time object.
.ofLocalizedTime( // Automatically localize the text being generated.
FormatStyle.SHORT // Specify how long or abbreviated the generated text should be.
) // Returns a `DateTimeFormatter` object.
.withLocale( Locale.US ) // Specifies a particular locale for the `DateTimeFormatter` rather than rely on the JVM’s current default locale. Returns another separate `DateTimeFormatter` object rather than altering the first, per immutable objects pattern.
) // Returns a `String` object.
上午 10:31
自动本地化
与其坚持使用 AM/PM 的 12 小时制,不如让java.time自动为您本地化。打电话DateTimeFormatter.ofLocalizedTime
。
要本地化,请指定:
在这里,我们获得了在特定时区看到的当前时间。然后我们生成文本来表示那个时间。我们在加拿大文化中本地化为法语,然后在美国文化中本地化为英语。
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalTime localTime = LocalTime.now( z ) ;
// Québec
Locale locale_fr_CA = Locale.CANADA_FRENCH ; // Or `Locale.US`, and so on.
DateTimeFormatter formatterQuébec = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale_fr_CA ) ;
String outputQuébec = localTime.format( formatterQuébec ) ;
System.out.println( outputQuébec ) ;
// US
Locale locale_en_US = Locale.US ;
DateTimeFormatter formatterUS = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale_en_US ) ;
String outputUS = localTime.format( formatterUS ) ;
System.out.println( outputUS ) ;
请参阅在 IdeOne.com 上实时运行的代码。
10 小时 31
上午 10:31