text

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.

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.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button