Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 425
giozh Avatar asked Aug 15 '13 16:08

giozh


People also ask

What is the format of Java sql date?

Formats a date in the date escape format yyyy-mm-dd. Converts a string in JDBC date escape format to a Date value.

How do you check if the date is today's date in Java?

DateTimeFormatter. The LocalDateTime. now() method returns the instance of LocalDateTime class. If we print the instance of LocalDateTime class, it prints the current date and time.

How do you write the current date in Java?

Code To Get Today's date in any specific Format getTime(); String todaysdate = dateFormat. format(date); System. out. println("Today's date : " + todaysdate);


1 Answers

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()); 
like image 108
rgettman Avatar answered Sep 29 '22 23:09

rgettman