java simpledateformat – Time and Date formatting with simpledateformat java class

The simpledateformat class

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

However in order to provide better reading like localized formatting and other date formatting java SimpleDateFormat class is the answer.

An example of simpledateformat class

You can use SimpleDateFormat class date formatting codes to display date as per requirements of your application. The examples below shows how to use SimpleDateFormat java class and formatting codes along with list of useful date formatting codes.

Using SimpleDateFormat class

This is how you will include SimpleDateFormat class in project:

import java.text.SimpleDateFormat;

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

Java SimpleDateFormat example

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

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 current time, formats and displays it. It also displays millisecond.

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 useful date format codes

The list below can be used to format dates with SimpleDateFormat java object. Following are formatting characters and its short description.

  • d = date in Month in digits e.g. 15
  • M = Month of year without leading zero (1,2, 12)
  • MM = Month with leading zero e.g. 01, 09
  • yy = last two digits of year e.g. 01, 02, 11
  • yyyy = 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 hour
  • s = second in minute
  • S = millisecond
  • z = time zone

Also see: Java date

Was this article helpful?

Related Articles

Leave A Comment?