Tuesday, December 8, 2009

Converting between different date formats in Java

It is often required to convert date from one format to another, for example from java.sql.Date('yyyy-MM-dd') to java.util.Date ('dd/MM/yyyy'). I wrote a generic function to do the job, which will convert from any given date format to another specified format. The method does not checks if the format provided is correct or not nor it checks if the date is a valid date or not.

I wrote this method to read dates from the database and to convert it to another format. It is assumed that the dates in the table are valid. Below is the code for the method.

public static String convertDate(String date, String sourceFormat, String destinationFormat) throws java.text.ParseException
{
    String returnDate="";
  
    SimpleDateFormat formatter = new SimpleDateFormat(sourceFormat);
    Date date1 = formatter.parse(date);

    formatter = new SimpleDateFormat(destinationFormat);
    returnDate = formatter.format(date1);
 
    return returnDate;
}

Usage: String newDate = convertDate("2009-12-08", "yyyy-MM-dd", "dd/MM/yyyy")
Output: date in dd/MM/yyyy format - 08/12/2009