Java Program to format date with SimpleDateFormat


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 += "'
Month = '"; strDate += "MMMMMMMMM"; strDate += "'
Hours = '"; strDate += "hh"; strDate += "a"; strDate += "'
Minutes = '"; strDate += "mm"; strDate += "'
Seconds = '"; 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 += "'
Month = '";       strDate += "MMMMMMMMM";        strDate += "'
Hours = '";       strDate += "hh";       strDate += "a";       strDate += "'
Minutes = '";       strDate += "mm";       strDate += "'
Seconds = '";       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
Samual Sam
Samual Sam

Learning faster. Every day.


Advertisements