[java] Get the current date in java.sql.Date format

I need to add the current date into a prepared statement of a JDBC call. I need to add the date in a format like yyyy/MM/dd.

I've try with

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
pstm.setDate(6, (java.sql.Date) date);

but I have this error:

threw exception
java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date

Is there a way to obtain a java.sql.Date object with the same format?

This question is related to java jdbc java.util.date

The answer is


Will do: new Date(Instant.now().toEpochMilli())


Since the java.sql.Date has a constructor that takes 'long time' and java.util.Date has a method that returns 'long time', I just pass the returned 'long time' to the java.sql.Date to create the date.

java.util.Date date = new java.util.Date();
java.sql.Date sqlDate = new Date(date.getTime());

new java.sql.Date(Calendar.getInstance().getTimeInMillis());

In order to get "the current date" (as in today's date), you can use LocalDate.now() and pass that into the java.sql.Date method valueOf(LocalDate).

import java.sql.Date;
...
Date date = Date.valueOf(LocalDate.now());

These are all too long.

Just use:

new Date(System.currentTimeMillis())

Simply in one line:

java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime());

You can achieve you goal with below ways :-

long millis=System.currentTimeMillis();  
java.sql.Date date=new java.sql.Date(millis);  

or

// create a java calendar instance
Calendar calendar = Calendar.getInstance();

// get a java date (java.util.Date) from the Calendar instance.
// this java date will represent the current date, or "now".
java.util.Date currentDate = calendar.getTime();

// now, create a java.sql.Date from the java.util.Date
java.sql.Date date = new java.sql.Date(currentDate.getTime());

all you have to do is this

    Calendar currenttime = Calendar.getInstance();               //creates the Calendar object of the current time
    Date sqldate = new Date((currenttime.getTime()).getTime());  //creates the sql Date of the above created object
    pstm.setDate(6, (java.sql.Date) date);              //assign it to the prepared statement (pstm in this case)

tl;dr

myPreparedStatement.setObject(   // Directly exchange java.time objects with database without the troublesome old java.sql.* classes.
    … ,                                   
    LocalDate.parse(             // Parse string as a `LocalDate` date-only value.
        "2018-01-23"             // Input string that complies with standard ISO 8601 formatting.
    ) 
)

java.time

The modern approach uses the java.time classes that supplant the troublesome old legacy classes such as java.util.Date and java.sql.Date.

For a date-only value, use LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

The java.time classes use standard formats when parsing/generating strings. So no need to specify a formatting pattern.

LocalDate ld = LocalDate.parse( input ) ;

You can directly exchange java.time objects with your database using a JDBC driver compliant with JDBC 4.2 or later. You can forget about transforming in and out of java.sql.* classes.

myPreparedStatement.setObject( … , ld ) ;

Retrieval:

LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to jdbc

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' Hibernate Error executing DDL via JDBC Statement Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] MySQL JDBC Driver 5.1.33 - Time Zone Issue Spring-Boot: How do I set JDBC pool properties like maximum number of connections? Where can I download mysql jdbc jar from? Print the data in ResultSet along with column names How to set up datasource with Spring for HikariCP? java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why? java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

Examples related to java.util.date

How to convert ZonedDateTime to Date? Get the current date in java.sql.Date format Convert java.util.date default format to Timestamp in Java How to subtract X day from a Date object in Java? How to add minutes to my Date Convert java.util.Date to String How to set time zone of a java.util.Date? Calculating the difference between two Java date instances