CommencerCommencer gratuitement

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.

Cet exercice fait partie du cours

Input/Output and Streams in Java

Afficher le cours

Instructions

  • Retrieve the current date.
  • Define a DateTimeFormatter with the pattern dd-MM-yyyy.
  • Format the current date using the formatter.
  • Parse a date string using the defined formatter.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de 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); 
    }
}
Modifier et exécuter le code