Search code examples
simpledateformatjava-6

convert a String date of format "dd/MM/yyyy HH:mm:ss" to * java.util.Date of format dd/mm/yyyy HH:mm:ss


/**
 * 
 * Purpose:
 * 
 * 1. Need to convert a String date of format "dd/MM/yyyy HH:mm:ss" to
 * java.util.Date of format dd/mm/yyyy HH:mm:ss and convert that to
 * java.sql.Date to send to database table column of type Date.
 *
 */
public class TestDate {

    public static void main(String[] args) throws ParseException {
        String inputDateStr = "10-Jan-2013";
        SimpleDateFormat inputFormatter = new SimpleDateFormat("dd-MMM-yyyy");
        SimpleDateFormat outputFormatter = new SimpleDateFormat(
                "dd/MM/yyyy HH:mm:ss");
        java.util.Date inputDateDate = inputFormatter.parse(inputDateStr);
        System.out.println("inputDateDate :" + inputDateDate);
        // printed: inputDateDate :Thu Jan 10 00:00:00 EST 2013

        String requiredDateStr = outputFormatter.format(inputDateDate);
        System.out.println("requiredDateStr :" + requiredDateStr);
        // printed: requiredDateStr :10/01/2013 00:00:00

        /*
         * PROBLEM: Need to convert this 'requiredDateStr' ie: '10/01/2013
         * 00:00:00' to a java.util.Date type and still retain the pattern of
         * "dd/MM/yyyy HH:mm:ss"
         */

        //how to do this?

        // java.util.Date requiredDateDate = feeding requiredDateStr and format
        // of "dd/MM/yyyy HH:mm:ss"

        // java.sql.Date sqlDate = new Date(requiredDateDate.getTime());

    }
}

Edit: Question: How to convert this String "10/01/2013 00:00:00" to java.util.Date format?

Ultimately I want to convert this String "10/01/2013 00:00:00" to a java.sql.Date format


Solution

  • Use SimpleDateFormat:

    SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss") ;
    df.parse("10/01/2013 00:00:00");
    

    See the documentation for more Information about the Format.

    For your second question see this thread.