Core JAVA

SimpleDateFormat in Java- format Date to String to Date with Example

SimpleDateFormat is an excellent utility class for formatting and parsing dates in a re-presentable manner. It allows for formatting Date to String and parsing String to Date. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. It is not thread-safe so its better you create separate DateFormat for each thread to avoid any race condition while parsing date in java.SimpleDateFormat class has two methods format() method to format Date to String and parse() method parse String to Date and time in java. It is a concrete class for formatting and parsing date which inherits java.text.DateFormat class.
  • format() formatting method means converting date to string
  • parse() parsing method means converting string to date

 

 

There various attributes available in SimpleDateFormat class in java for pattern, As per Java Doc following:

Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day in week Text Tuesday; Tue
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800


SimpleDateFormat Example in Java

Format Date to String

In this example we are going to format dates using SimpleDateFormat. We can format Date to String to our defined format e.g “dd-MM-yyyy”. This format will print dates in that format e.g. 20-02-2017. We can define any format by using letter patterns supported by SimpleDateFormat in java e.g. d means day of month, y means year and M means Month of year as mention in above list in this tutorial. There following steps to convert date to string:

  • Step 1: Create a valid date format using SimpleDateFormat as you wanna display upfront
  • Step 2: Then call format() method of SimpleDateFormat and passed Date object as argument of this method, it will return String format of date as you specified in the first step.

Let’s see the simple example to format date in java using java.text.SimpleDateFormat class.

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 
 */

/**
 * @author Dinesh.Rajput
 *
 */
public class SimpleDateFormatExample {

 /**
  * @param args
  */
 public static void main(String[] args) {
  //Creating Date in java with today's date.
    Date todayDate = new Date();

    //change date to string on dd-MM-yyyy format e.g. "20-02-2017"
    SimpleDateFormat dateformater_Java = new SimpleDateFormat("dd-MM-yyyy");
    String todayDateStr = dateformater_Java.format(todayDate);
    System.out.println("Today's date into dd-MM-yyyy format: " + todayDateStr);
    
    //converting date to string dd/MM/yyyy format for example "20/02/2017"
    SimpleDateFormat formatDateJava = new SimpleDateFormat("dd/MM/yyyy");
    todayDateStr = formatDateJava.format(todayDate);
    System.out.println("Today's date into dd/MM/yyyy format: " + todayDateStr);
      
    //change date into string yyyyMMdd format example "20170220"
    SimpleDateFormat dateformater_yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
    todayDateStr = dateformater_yyyyMMdd.format(todayDate);
    System.out.println("Today's date into yyyyMMdd format: " + todayDateStr);

 }

}

Output:
Today’s date into dd-MM-yyyy format: 20-02-2017
Today’s date into dd/MM/yyyy format: 20/02/2017
Today’s date into yyyyMMdd format: 20170220

Parse String to Date

java.text.SimpleDateFormat class is also used to format Date to String as date and time. SimpleDateFormat formats date in same pattern whatever we are provided to it while creating instance of SimpleDateFormat. So we can also include time information like hour, minutes and seconds while formatting dates.

Let’s see the full example to format date and time in java using java.text.SimpleDateFormat class.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 
 */

/**
 * @author Dinesh.Rajput
 *
 */
public class SimpleDateFormatExample {

 /**
  * @param args
  */
 public static void main(String[] args) {
  
  //parse string to date dd/MM/yyyy format e.g. "20-02-2017"
  SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");  
  try {  
   Date date = formatter.parse("20/02/2017");  
         System.out.println("Date is: "+date);  
  } catch (ParseException e) {
   e.printStackTrace();
  }  
     
  //parse string to date dd-MM-yyyy format e.g. "20-02-2017"
  formatter = new SimpleDateFormat("dd-MM-yyyy");  
  try {  
   Date date = formatter.parse("20-02-2017");  
         System.out.println("Date is: "+date);  
  } catch (ParseException e) {
   e.printStackTrace();
  }  
     
       }

}

Output:
Date is: Mon Feb 20 00:00:00 IST 2017
Date is: Mon Feb 20 00:00:00 IST 2017

Summary
In this tutorial we have seen how to format date to string and parse string to date using SimpleDateFormat with example. There are two methods exists in this concrete class format() and parse(). format() used for formatting means converting date to string and parse() used for parsing means converting string to date.

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago