Formatting and parsing dates
Formatting and parsing dates are essential for working with different date representations. In this exercise, you will format a date and parse a string into a LocalDate
.
This exercise is part of the course
Input/Output and Streams in Java
Exercise instructions
- Retrieve the current date.
- Define a
DateTimeFormatter
with the patterndd-MM-yyyy
. - Format the current date using the formatter.
- Parse a date string using the defined formatter.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateExample {
public static void main(String[] args) {
// Get current date
LocalDate date = ____;
System.out.println("current date in default format: " + date);
// Define format with pattern dd-MM-yyyy
DateTimeFormatter formatter = DateTimeFormatter.____("dd-MM-yyyy");
// Format and print date
System.out.println(date.____(formatter));
// Parse a text into string
LocalDate parseDate = LocalDate.____("2025-02-10");
System.out.println("Parse the text into date: " + parseDate);
}
}