Java Program to format date with SimpleDateFormat

Java 8Object Oriented ProgrammingProgramming

The SimpleDateFormat class is used to parse and format dates. To create an object, firstly import the following package

import java.text.SimpleDateFormat;

Set the date

String strDate = "'Year = '";
strDate += "yyyy";
strDate += "'\nMonth = '";
strDate += "MMMMMMMMM";
strDate += "'\nHours = '";
strDate += "hh";
strDate += "a";
strDate += "'\nMinutes = '";
strDate += "mm";
strDate += "'\nSeconds = '";
strDate += "ss";

Now, create an object and format the date −

SimpleDateFormat dateFormat = new SimpleDateFormat(strDate);
String formattedDate = dateFormat.format(new Date());

The following is an example −

Example

 Live Demo

import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
   public static void main(String args[]) {
      String strDate = "'Year = '";
      strDate += "yyyy";
      strDate += "'\nMonth = '";
      strDate += "MMMMMMMMM";
       strDate += "'\nHours = '";
      strDate += "hh";
      strDate += "a";
      strDate += "'\nMinutes = '";
      strDate += "mm";
      strDate += "'\nSeconds = '";
      strDate += "ss";
      System.out.println("Date and Time....");
      SimpleDateFormat dateFormat = new SimpleDateFormat(strDate);
      String formattedDate = dateFormat.format(new Date());
      System.out.println(formattedDate);
   }
}

Output

Date and Time....
Year = 2018
Month = November
Hours = 09AM
Minutes = 12
Seconds = 41
raja
Published on 19-Dec-2018 05:45:59
Advertisements