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.