Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Calendar to java.sql.Date in Java?

Tags:

java

sql

calendar

Calendar cal; String sql = "INSERT INTO ttable (dt) values (?);" //dt is a dateTime field in ttable  PreparedStatement stmt = connection.prepareStatement(sql);  stmt = setDate(1,cal); //not working  stmt.execute(); stmt.close(); 

I would like to convert cal to a Date type to insert into table.

like image 633
Alex Avatar asked Feb 02 '12 13:02

Alex


People also ask

How do I get current date in sql Java?

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) .


2 Answers

There is a getTime() method (unsure why it's not called getDate).

Edit: Just realized you need a java.sql.Date. One of the answers which use cal.getTimeInMillis() is what you need.

like image 171
Jim Avatar answered Oct 01 '22 07:10

Jim


Use stmt.setDate(1, new java.sql.Date(cal.getTimeInMillis()))

like image 42
James Jithin Avatar answered Oct 01 '22 06:10

James Jithin