📜  Java Internationalizing Date (I18N with Date)(1)

📅  最后修改于: 2023-12-03 15:31:30.763000             🧑  作者: Mango

Java Internationalizing Date (I18N with Date)

Java Internationalizing Date (I18N with Date) refers to the process of formatting date and time in a way that is readable and understandable to people from different regions and cultures. Java provides various classes and packages for formatting dates and time in different formats as per the user's requirements. In this article, we will look at some of the ways Java provides for Internationalizing Dates.

ResourceBundle

Java ResourceBundle is an abstract class that is used to create a specialized set of classes that are capable of handling localized resources. It enables programmers to load properties and strings from a specified file and then use the same in their code. Resource bundles help to provide the flexibility to create and modify localization data without modifying the code.

ResourceBundle resourceBundle = ResourceBundle.getBundle("i18n/DateTimeMessages");
String format = resourceBundle.getString("date.format");
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(format);
String formattedDate = formatter.format(date);
System.out.println(formattedDate);

The above code loads the DateTimeMessages bundle from the i18n package and gets the date.format property which specifies the format for the date. The SimpleDateFormat class is used to format the date as per the specified format.

DateTimeFormatter

Java 8 introduced a new package called java.time that provides improved date and time formatting classes. One of the classes in the package is the DateTimeFormatter class, which provides support for formatting and parsing date-time objects.

Locale locale = Locale.JAPAN;
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(locale);
ZonedDateTime date = ZonedDateTime.now();
System.out.println(formatter.format(date));

The above code creates a DateTimeFormatter object that takes the locale as an argument and then sets the date time format as per the locale.

DateFormat

DateFormat is an abstract class that is used to format and parse dates and times. It is a part of the java.text package that provides several classes for handling text, number, and date and time formatting.

Locale locale = new Locale("fr", "FR");
DateFormat formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
Date date = new Date();
System.out.println(formatter.format(date));

The above code creates a DateFormat object for a French locale and sets the date format as medium. The format() method is then used to format the date.

In conclusion, Java provides various built-in classes and packages for formatting dates and times in different formats. These classes enable programmers to internationalize their applications and provide a better user experience to users from different regions and cultures.