Printing Original Dates
To print the original date represented by a LocalDate
object, you can use the toString()
method. This method returns a string representation of the date in the ISO-8601 format (YYYY-MM-DD).
LocalDate today = LocalDate.now();
System.out.println("Original date: " + today); // Output: Original date: 2023-04-18
Alternatively, you can use the print()
method of the DateTimeFormatter
class to customize the output format of the date.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String formattedDate = today.format(formatter);
System.out.println("Formatted date: " + formattedDate); // Output: Formatted date: 18/04/2023
In the example above, the DateTimeFormatter.ofPattern("dd/MM/yyyy")
creates a formatter that displays the date in the format "day/month/year". You can customize the format string to suit your needs.
Printing Dates with Locales
If you need to print dates in a specific locale, you can use the DateTimeFormatter
class with a Locale
object.
Locale frLocale = Locale.FRANCE;
DateTimeFormatter frenchFormatter = DateTimeFormatter.ofPattern("dd MMMM yyyy", frLocale);
String frenchDate = today.format(frenchFormatter);
System.out.println("French date: " + frenchDate); // Output: French date: 18 avril 2023
In this example, the Locale.FRANCE
object is used to format the date in the French locale, displaying the month name in French.
By understanding how to print original dates using the LocalDate
class and the DateTimeFormatter
, you can effectively display dates in your Java applications.