Java - Legacy Date Time Custom Formatting

Introduction

To create custom date formats, use the SimpleDateFormat class.

Formatting using the SimpleDateFormat class is locale-sensitive.

You can call SimpleDateFormat format() method to format the date.

To change the date format for subsequent formatting, use the applyPattern() method by passing the new date pattern as an argument.

For example,

Demo

import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
  public static void main(String[] args) {
    // Create a formatter with a pattern dd/MM/yyyy. 
    SimpleDateFormat simpleFormatter = new SimpleDateFormat("dd/MM/yyyy");

    // Get current date
    Date today = new Date();

    // Format the current date
    String formattedDate = simpleFormatter.format(today);

    // Print the date
    System.out.println("Today is (dd/MM/yyyy): " + formattedDate);

    // Change the date format. Now month will be spelled fully.
    // Note a comma will appear as a comma. It has no special interpretation.
    simpleFormatter.applyPattern("MMMM dd, yyyy");

    // Format the current date
    formattedDate = simpleFormatter.format(today);

    // Print the date
    System.out.println("Today is (MMMM dd, yyyy): " + formattedDate);

  }//  ww w .  j a v  a  2  s. c  om
}

Result

Related Topics

Exercise