📅  最后修改于: 2023-12-03 14:42:14.560000             🧑  作者: Mango
Java provides extensive support for internationalization (I18N) to help developers create applications that can be easily localized and adapted to different languages and cultural environments. One aspect of I18N is the handling of date and time formats, which can vary widely across different countries and regions. In this article, we will discuss how to internationalize time in Java and provide examples of how to format time for different locales.
The java.time package introduced in Java 8 provides a modern date and time API that allows for easy formatting and parsing of dates and times. To format time for a specific locale, we can use the DateTimeFormatter class.
LocalTime currentTime = LocalTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(Locale.GERMANY);
String formattedTime = currentTime.format(formatter);
System.out.println(formattedTime);
In this example, we create a LocalTime object representing the current time, create a DateTimeFormatter object using the ofLocalizedTime() method to specify a SHORT format style, and set the locale to Germany using the withLocale() method. We then use the format() method to format the time as a string according to the specified locale. The resulting output will be a formatted time string for Germany:
13:21
Similarly, we can format time for different locales by changing the locale parameter. For example, to format time for the United States, we can set the locale to Locale.US:
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(Locale.US);
In some cases, we may need to use time constants in our application, such as when setting default values or specifying event times. To localize time constants, we can use the ZonedDateTime class.
ZonedDateTime eventTime = ZonedDateTime.of(2021, 9, 1, 8, 0, 0, 0, ZoneId.systemDefault());
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withLocale(Locale.FRANCE);
String formattedEventTime = eventTime.format(formatter);
System.out.println(formattedEventTime);
In this example, we create a ZonedDateTime object representing a specific event time (September 1st 2021, 8AM), create a DateTimeFormatter object using the ofLocalizedDateTime() method to specify a MEDIUM format style, and set the locale to France using the withLocale() method. We then use the format() method to format the event time as a string according to the specified locale. The resulting output will be a formatted event time string for France:
1 sept. 2021 08:00:00
In summary, Java provides powerful support for internationalizing time through the java.time package. By using the DateTimeFormatter class, we can easily format time for different locales, allowing our applications to be easily adapted for different cultures and regions.