Java Program to Do Date Format and Manipulation

01. Example:

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

public class simpleDateFormatManipulation {
  public static void main(String[] args) {
    
    Date date = new Date();
    
    System.out.println("Date Format And Manipulationn___________________________________");
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
	  String dateString = formatter.format(date);
    System.out.println("nnDate Format (MM/dd/yyyy): " + dateString);

    formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
    dateString = formatter.format(date);
    System.out.println("nDate Format (dd-M-yyyy hh:mm:ss): " + dateString);

    formatter = new SimpleDateFormat("dd MMMM yyyy");
    dateString = formatter.format(date);
    System.out.println("nDate Format (dd MMMM yyyy): " + dateString);

    formatter = new SimpleDateFormat("dd MMMM yyyy zzzz");
    dateString = formatter.format(date);
    System.out.println("nDate Format (dd MMMM yyyy zzzz): " + dateString);

    formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
    dateString = formatter.format(date);
    System.out.println("nDate Format (E, dd MMM yyyy HH:mm:ss z): " + dateString);
  }
}

Output:

Date Format And Manipulation
___________________________________


Date Format (MM/dd/yyyy): 02/05/2023

Date Format (dd-M-yyyy hh:mm:ss): 05-2-2023 07:00:54

Date Format (dd MMMM yyyy): 05 February 2023

Date Format (dd MMMM yyyy zzzz): 05 February 2023 Coordinated Universal Time

Date Format (E, dd MMM yyyy HH:mm:ss z): Sun, 05 Feb 2023 19:00:54 UTC

This Java code uses the java.text.SimpleDateFormat class to format and manipulate the representation of a java.util.Date object.

The code first creates a java.util.Date object, which represents the current date and time, using the default constructor.

Then, it creates several instances of the SimpleDateFormat class, each with a different pattern string that defines the desired date and time format. The pattern string uses special characters, such as “MM” for the month, “dd” for the day of the month, “yyyy” for the year, “hh” for the hour in a 12-hour clock, “mm” for the minute, “ss” for the second, “zzzz” for the time zone, “E” for the day of the week, and “z” for the time zone in the format “GMT+hh:mm”.

For each instance of the SimpleDateFormat class, the code calls the format method and passes the date object as an argument. This method returns a string representation of the date object, formatted according to the pattern string.


Leave a comment