Skip to Content

Convert date string from one format to another format using SimpleDateFormat

  1. /*
  2.   Convert date string from one format to another format using SimpleDateFormat
  3.   This example shows how to convert format of a string containing date
  4.   and time to other formats using Java SimpleDateFormat class.
  5. */
  6.  
  7. import java.util.Date;
  8. import java.text.ParseException;
  9. import java.text.SimpleDateFormat;
  10.  
  11. public class ConvertDateFormats {
  12.  
  13.   public static void main(String[] args) {
  14.    
  15.     //string containing date in one format
  16.     String strDate = "12/12/07";
  17.    
  18.     try
  19.     {
  20.       //create SimpleDateFormat object with source string date format
  21.       SimpleDateFormat sdfSource = new SimpleDateFormat("dd/MM/yy");
  22.      
  23.       //parse the string into Date object
  24.       Date date = sdfSource.parse(strDate);
  25.      
  26.       //create SimpleDateFormat object with desired date format
  27.       SimpleDateFormat sdfDestination = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
  28.      
  29.       //parse the date into another format
  30.       strDate = sdfDestination.format(date);
  31.      
  32.       System.out.println("Date is converted from dd/MM/yy format to MM-dd-yyyy hh:mm:ss");
  33.       System.out.println("Converted date is : " + strDate);
  34.      
  35.     }
  36.     catch(ParseException pe)
  37.     {
  38.       System.out.println("Parse Exception : " + pe);
  39.     }
  40.   }
  41. }
  42.  
  43. /*
  44. Typical output would be
  45. Date is converted from dd/MM/yy format to MM-dd-yyyy hh:mm:ss
  46. Converted date is : 12-12-2007 12:00:00
  47. */