How to parse String to java.sql.date

谁说胖子不能爱 提交于 2019-12-01 17:16:05

Use SimpleDateFormat to parse String date to java.util.Date

java.util.Date utilDate = new SimpleDateFormat("dd MMM yyyy").parse("01 NOVEMBER 2012");

and then convert it to java.sql.Date using millis

java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

Expanding on Jigar Joshi answer.

This code has been able to handle whatever I've needed.

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

Date date1;
Date date2;
Date date3;

    //converting string into sql date);
    try {
         date1 = new java.sql.Date(
                     ((java.util.Date) new SimpleDateFormat("dd MMM yyyy").parse("01 NOVEMBER 2012")).getTime());

        date2 = new java.sql.Date(
                    ((java.util.Date)newSimpleDateFormat("dd/MM/yyyy").parse("02/09/2012")).getTime());

        date3 = new java.sql.Date(
                    ((java.util.Date) new SimpleDateFormat("ddMMyyyy").parse("03092012")).getTime());

    } catch (ParseException e) {
            e.printStackTrace();
        }

    System.out.println("sqlDate test1:" + date1);
    System.out.println("sqlDate test2:" + date2);
    System.out.println("sqlDate test3:" + date3);


    output:
           sqlDate test1:2012-11-01
           sqlDate test2:2012-09-02
           sqlDate test3:2012-09-03
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!