formatting dates using SimpleDateFormat

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Hello all, in this tutorial we are going to learn how to format dates and printing them. Java provides a great API just for this called as SimpleDateFormat . This is straight from oracle’s official javadocs.

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization.

You can take any date object and then use it to form a meaningful representation. We will use string patterns for the same purpose.

Consider we want to print current time in the format DD/MM/YYYY . We will have to use the pattern like "dd/MM/YYYY" .

  • dd represents the day of the month.
  • MM represents name of the month.
  • YYYY represents year.

Consider this example.

This prints 06/08/2013 .

  • In the string, dd/MM/YYYY the letters dd, MM and YYYY have the meaning.Slashes are just used as separator.
  • You can have anything as separator, only the valid formats will be recognized which can be referred from  SimpleDateFormat javadoc.

This program illustrates mostly used formats.

This outputs



Share Button

5 comments for “formatting dates using SimpleDateFormat

  1. July 31, 2014 at 10:15 pm

    Nice article Prasad.
    I would like to know, Is it the right thing to use if we have to format Date always.

    • August 1, 2014 at 10:34 am

      Hi Shanky. Thank you for reading, there is nothing wrong in formatting dates with SimpleDateFormat.

  2. sumit
    May 6, 2016 at 3:15 pm

    can we use object pooling to save the resources when it each time creates object using new keyword. how can we do that

    • May 6, 2016 at 3:47 pm

      You can use it as static variable or retrieve through singleton variable or from some factory pattern.

  3. Alex
    May 26, 2017 at 5:18 am

    Hi Prasad,

    I am trying to use format “yyyy-MM-dd’T’HH:mm:ss.SSSXXX”, but the result is wrong. Can you have a look.

    1. there is a string adjustmentDateTime = “2016-12-03 10:43:51.15”
    2. parse adjustmentDaeTime to Date with format “yyyy-MM-dd HH:mm:ss.SSS” (until now, the millsecond is correct, it is “1475700531150”)
    3. format the date to a string with format “yyyy-MM-dd’T’HH:mm:ss.SSSXXX”.

    The actual result is “2016-10-05T13:48:51.015-07:00”
    but the expected result should be “2016-10-05T13:48:51.150-07:00”.
    Do you have some ideas?

Leave a Reply

Your email address will not be published. Required fields are marked *