Menu
Coddy logo textTech

Date Formatting

Part of the Logic & Flow section of Coddy's Java journey — lesson 58 of 59.

DateTimeFormatter in Java allows you to format dates and times in different patterns. It can be used with LocalDate, LocalTime, and LocalDateTime.

Create a formatter with a specific pattern:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

Format a date using the formatter:

LocalDate date = LocalDate.of(2024, 3, 15);
String formatted = date.format(formatter);

After executing the above code, formatted contains:

2024-03-15

Parse a string into a date:

String dateStr = "2024-03-15";
LocalDate date = LocalDate.parse(dateStr, formatter);
challenge icon

Challenge

Easy

Create a method named formatDate that takes three arguments:

  1. A String (dateStr) in format "yyyy-MM-dd"
  2. A String (inputPattern) the pattern of input date
  3. A String (outputPattern) the desired output pattern

The method should:

  1. Parse the input date using the input pattern
  2. Format it using the output pattern
  3. Handle these patterns:
    • "basic": "yyyy-MM-dd"
    • "long": "MMMM d, yyyy"
    • "short": "MM/dd/yy"
    • "custom": The actual pattern string

Return messages should be:

  • If invalid date: return "Invalid date format"
  • If invalid pattern: return "Invalid pattern"
  • For success: return the formatted date

Cheat sheet

DateTimeFormatter allows you to format dates and times with specific patterns:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

Format a date using the formatter:

LocalDate date = LocalDate.of(2024, 3, 15);
String formatted = date.format(formatter);

Parse a string into a date:

String dateStr = "2024-03-15";
LocalDate date = LocalDate.parse(dateStr, formatter);

Try it yourself

import java.util.Scanner;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class Main {
    public static String formatDate(String dateStr, String inputPattern, String outputPattern) {
        // Write your code here
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String dateStr = scanner.nextLine();
        String inputPattern = scanner.nextLine();
        String outputPattern = scanner.nextLine();
        
        System.out.println(formatDate(dateStr, inputPattern, outputPattern));
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow