转换格式的字符串日期" dd / MM / yyyy HH:mm:ss" to * java.util.Date格式为dd / mm / yyyy HH:mm:ss

时间:2015-02-26 17:07:08

标签: simpledateformat java-6

/**
 * 
 * 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());

    }
}

编辑:问题:如何转换此字符串" 10/01/2013 00:00:00"到java.util.Date格式?

最终我想转换这个字符串" 10/01/2013 00:00:00"到java.sql.Date格式

1 个答案:

答案 0 :(得分:1)

使用SimpleDateFormat:

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

有关格式的详细信息,请参阅documentation

关于第二个问题,请参阅this thread