Home » Core Java » text » Convert dates between formats with SimpleDateFormat

About Byron Kiourtzoglou

Byron Kiourtzoglou
Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Convert dates between formats with SimpleDateFormat

In this example we shall show you how to convert dates between formats with SimpleDateFormat. To convert dates between formats with SimpleDateFormat one should perform the following steps:

  • Create a new String to be used as the date that will be parsed by the SimpleDateFormat.
  • Create a new SimpleDateFormat, using a String pattern to describe the date and time format.
  • Invoke the parse(String source) API method to parse the given date string and produce a Date parsed from the string.
  • Create a new SimpleDateFormat, using a different String pattern.
  • Invoke the format(Date date) API method to format the produced date into a new date String,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

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

public class ConvertDatesBetweenFormatsWithSimpleDateFormat {
	
	public static void main(String[] args) {
		
		try {
			
			String dateStr = "21/20/2011";
			
			DateFormat srcDf = new SimpleDateFormat("dd/MM/yyyy");
			
			// parse the date string into Date object
			Date date = srcDf.parse(dateStr);
			
			DateFormat destDf = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
			 
			// format the date into another format
			dateStr = destDf.format(date);
			
			System.out.println("Converted date is : " + dateStr);
			
		}
		catch (ParseException e) {
			e.printStackTrace();
		}
		
	}

}

Output:

Converted date is : 08-21-2012 12:00:00

 
This was an example of how to convert dates between formats with SimpleDateFormat in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of