Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse String to java.sql.date

I have a String

String s = "01 NOVEMBER 2012";

Then I want parse it to sqlDate. And insert it into the database.

Is it possible to parse that string to sqlDate?!?!

Yup, sql date format is "yyyy-mm-dd"

like image 275
Jason Amavisca Avatar asked Oct 11 '12 16:10

Jason Amavisca


People also ask

Can we convert string to date in Java?

We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.

What is parse date in sql?

The PARSE() function is pretty smart, in that, if you provide the wrong weekday, it will return an error. So if we use the same date as the previous examples, but we change the weekday from Friday to Thursday, here's what happens: SELECT PARSE('Thursday, 20 July 2018' AS date) AS 'Result';


2 Answers

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());
like image 176
jmj Avatar answered Oct 13 '22 22:10

jmj


java.time

I am providing the modern answer. I recommend that you use java.time, the modern Java date and time API, for your date work.

    DateTimeFormatter dateFormatter = 
        new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("dd MMMM uuuu")
            .toFormatter(Locale.ENGLISH);
    
    String s = "01 NOVEMBER 2012";
    
    LocalDate date = LocalDate.parse(s, dateFormatter);
    
    System.out.println(date);

Output:

2012-11-01

You asked for a java.sql.Date? By all likelihood you don’t need any. I assume that you wanted one for use with your SQL database. Since JDBC 4.2 you can use LocalDate there too. For example:

    PreparedStatement statement = yourDatabaseConnection.prepareStatement(
            "insert into your_table (your_date_column) values (?);");
    statement.setObject(1, date);
    statement.executeUpdate();

Note the use of PreparedStatement.setObject() (not setDate()).

If you do need a java.sql.Date for a legacy API not yet upgraded to java.time, the conversion is easy and straightforward:

    java.sql.Date oldfashionedJavaSqlDate = java.sql.Date.valueOf(date);
    System.out.println(oldfashionedJavaSqlDate);

2012-11-01

Links

  • Oracle tutorial: Date Time explaining how to use java.time.
  • Related question: Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2
like image 45
Ole V.V. Avatar answered Oct 13 '22 22:10

Ole V.V.