2 examples for formatting dates by Java SimpleDateFormat class

The SimpleDateFormat class

The simple Date class of java.util package does not provide enough methods to work with the date formatting in Java applications. The Date() class is good to use if you intend to work with the current date.

However, in order to provide better reading like localized formatting and some other date formatting features, the Java SimpleDateFormat class is the answer.

An example of SimpleDateFormat class

You can use the SimpleDateFormat class’s date formatting codes to display the date as per the requirements of your application. The examples below show how to use the SimpleDateFormat Java class and formatting codes along with the list of useful date formatting codes.

Using SimpleDateFormat class

This is how you will include the SimpleDateFormat class in a project:

import java.text.SimpleDateFormat;

As you can see, the SimpleDateFormat is the part of the java.text package.

Java SimpleDateFormat example

The example below shows a few date formatting codes to display current date by using the SimpleDateFormat class.

Experience this online

The output will be:

Current Date in dd/MM/yyyy format: 15/01/2011

Current Date in MM/dd/yyyy format: 01/15/2011

Current Date and time in MM/dd/yyyy format: 01/15/2011 06:07:45

Get current time example by SimpleDateFormat class

This example gets the current time, formats and displays it. It also displays the Milliseconds.

Experience this online

The output will be:

Current time in 24 hours format: 18:55:43

Current time in 12 hours format: 6:55:43  255

SimpleDateFormat class and date formatting codes

The codes in the following list can be used to format dates with the SimpleDateFormat object. Following are the date formatting characters and their short description.

  • d = The date of Month in digits e.g. 15.
  • M = Month of the year without a leading zero (1,2, 12).
  • MM = Month with a leading zero e.g. 01, 09.
  • yy = Last two digits of the year e.g. 01, 02, 11.
  • yyyy = The Year in four digits e.g. 2001, 2011.
  • E = Day name in Week (Mon, Tue, Wed).
  • D = Number of day in year.
  • h = Hour in AM or PM format e.g. 1,5,6.
  • H = Hour in 24 format e.g. 18, 19, 23.
  • m = Minute in an hour.
  • s = Second in the minute.
  • S = Millisecond.
  • z = Time zone.

Useful reading – Java date | printf method to format dates