How do you use DateTimeFormatter i18n with a simple code example?

DateTimeFormatter is a powerful class in Java that allows you to format date and time in various locales, making it useful for internationalization (i18n). Below is a simple code example demonstrating how to use DateTimeFormatter with different locales.

import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Locale; public class DateTimeFormatterExample { public static void main(String[] args) { LocalDateTime dateTime = LocalDateTime.now(); // Formatting for US locale DateTimeFormatter formatterUS = DateTimeFormatter.ofPattern("MMMM dd, yyyy hh:mm a", Locale.US); String formattedUS = dateTime.format(formatterUS); System.out.println("US Format: " + formattedUS); // Formatting for France locale DateTimeFormatter formatterFR = DateTimeFormatter.ofPattern("d MMMM yyyy à HH:mm", Locale.FRANCE); String formattedFR = dateTime.format(formatterFR); System.out.println("France Format: " + formattedFR); } }

DateTimeFormatter i18n internationalization Java Date and Time formatting