73

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?

Marc-Andre
  • 912
  • 1
  • 15
  • 34
giozh
  • 9,868
  • 30
  • 102
  • 183
  • 1
    Depending on your use-case, you might not want to send the date from the client. Instead, have an insert trigger on the table to set the column to "now" on the db server side. This way you can have a consistent server side timestamp, protect yourself from client side clock/timezone problems, and have new records still have the date updated if the records are inserted from a different client app or addhoc transaction. – Glenn Aug 15 '13 at 23:55

10 Answers10

113

A java.util.Date is not a java.sql.Date. It's the other way around. A java.sql.Date is a java.util.Date.

You'll need to convert it to a java.sql.Date by using the constructor that takes a long that a java.util.Date can supply.

java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • 1
    What about the current date? – Yster Dec 11 '15 at 11:42
  • 2
    @Yster The question already had the current date: `Date date = new Date();`. It's about converting a `java.util.Date` to a `java.sql.Date`. – rgettman Dec 11 '15 at 17:36
  • 27
    For simplicity's sake: java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis()); – vedi0boy Nov 04 '16 at 22:22
  • 6
    downvote - no idea what a utilDate is or how your code is meant to compile. unclear. – bharal Feb 12 '17 at 18:44
  • 2
    @bharal The naming convention is quite clearly "sqlDate" and "utilDate" (`java.sql.Date`, `java.util.Date`). The code compiles in any block in which a `java.util.Date` exists with the name "utilDate". The question was about converting a date, implying one already exists. – cossacksman Feb 12 '17 at 21:16
  • java.sql.Date is deprecated !! – Ahmed Elbatt Jan 28 '20 at 02:18
  • 2
    @AhmedElbatt but the answer is still valid. The question asks how to convert one Class to the other. – algiogia Jan 14 '21 at 16:44
51

These are all too long.

Just use:

new Date(System.currentTimeMillis())
Grant Miller
  • 27,532
  • 16
  • 147
  • 165
Ethan Conner
  • 572
  • 5
  • 11
  • 1
    How can I get it to this format 2020-05-27T16:28:15.759+0200 and not as it is 2020-05-27 ? Thanks – JBD May 27 '20 at 14:48
  • If you're wanting an offset, you'll likely need to be using OffsetDateTime class and persisting it as a string. However, be warned that offsets will have trouble with daylight savings. – Ethan Conner Jun 01 '20 at 15:10
45

Simply in one line:

java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime());
kelevra88
  • 1,532
  • 3
  • 17
  • 25
21
new java.sql.Date(Calendar.getInstance().getTimeInMillis());
Amala
  • 1,718
  • 1
  • 17
  • 29
5

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());
pamcevoy
  • 1,136
  • 11
  • 15
4

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());
AExplosion
  • 51
  • 2
3

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
3

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

Andrey Lebedenko
  • 1,850
  • 17
  • 24
0

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());
duggu
  • 37,851
  • 12
  • 116
  • 113
0

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)
muhammed aslam
  • 44
  • 1
  • 11