DateFormat

DateFormat is an abstract class in the java.text package used to format and parse dates and times in a locale-sensitive manner. It is often used to convert Date objects to readable strings and parse strings back into Date objects.

Key Features

  • Format Date to String
  • Parse String to Date
  • Locale-sensitive formatting
  • Supports different styles (FULL, LONG, MEDIUM, SHORT)

Commonly Used Methods

Simple Program

import java.text.DateFormat;
import java.util.Date;

public class SimpleDateFormatExample {
    public static void main(String[] args) {
        Date currentDate = new Date();

        DateFormat df = DateFormat.getDateInstance(DateFormat.FULL);
        String formatted = df.format(currentDate);

        System.out.println("Current Date: " + formatted);
    }
}
/*
Current Date: Friday, May 23, 2025
*/

Problem Statement

Paani and Mahesh are building a Bank Statement Generator. Each transaction must display:

  • Transaction Date (formatted for readability)
  • Description
  • Amount
  • Type (Credit/Debit)

Use the DateFormat class to convert Date objects into human-readable strings for the bank statement.

import java.text.DateFormat;
import java.util.Date;

class Transaction {
    Date date;
    String description;
    double amount;
    String type;

    public Transaction(Date date, String description, double amount, String type) {
        this.date = date;
        this.description = description;
        this.amount = amount;
        this.type = type;
    }
}

public class BankStatementGenerator {
    public static void main(String[] args) {
        Transaction[] transactions = {
            new Transaction(new Date(125, 4, 23), "ATM Withdrawal", 1500.00, "Debit"),
            new Transaction(new Date(125, 4, 21), "Salary Credit", 50000.00, "Credit"),
            new Transaction(new Date(125, 4, 19), "Online Shopping", 2500.50, "Debit")
        };

        DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);

        System.out.println("----- Bank Statement -----");
        System.out.printf("%-20s %-25s %-10s %-10s\n", "Date", "Description", "Amount", "Type");

        for (Transaction t : transactions) {
            String formattedDate = df.format(t.date);
            System.out.printf("%-20s %-25s ₹%-9.2f %-10s\n", formattedDate, t.description, t.amount, t.type);
        }
    }
}
/*
----- Bank Statement -----
Date                 Description               Amount     Type      
May 23, 2025         ATM Withdrawal            ₹1500.00   Debit     
May 21, 2025         Salary Credit             ₹50000.00  Credit    
May 19, 2025         Online Shopping           ₹2500.50   Debit     
*/

The DateFormat class is essential for applications that require human-readable date/time output or parsing input dates. It’s especially helpful in internationalized or professional contexts like:

  • Bank statements
  • Reports
  • UI displays
  • Logging systems
Scroll to Top