Alex
Alex

Reputation: 3405

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

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.

Upvotes: 71

Views: 229234

Answers (8)

Victor Martin
Victor Martin

Reputation: 41

Calendar cal = Calendar.getInstance(); //This to obtain today's date in our Calendar var.

java.sql.Date date = new Date (cal.getTimeInMillis());

Upvotes: 4

Jim
Jim

Reputation: 22656

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.

Upvotes: 141

Steve Pitchers
Steve Pitchers

Reputation: 7374

stmt.setDate(1, new java.sql.Date(cal.getTime().getTime()));

Upvotes: 4

Kurt Du Bois
Kurt Du Bois

Reputation: 7665

Did you try cal.getTime()? This gets the date representation.

You might also want to look at the javadoc.

Upvotes: 35

David Ophiuchus
David Ophiuchus

Reputation: 137

Here is a simple way to convert Calendar values into Date instances.

Calendar C = new GregorianCalendar(1993,9,21);

Date DD = C.getTime();

System.out.println(DD);

Upvotes: 9

Orit
Orit

Reputation: 21

I found this code works:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");    
Calendar calendar = new GregorianCalendar(2013,0,31);
System.out.println(sdf.format(calendar.getTime()));  

you can find the rest in this tutorial:
http://www.mkyong.com/java/java-date-and-calendar-examples/

Upvotes: 2

rebeliagamer
rebeliagamer

Reputation: 1278

Converting is easy, setting date and time is a little tricky. Here's an example:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 1);
cal.set(Calendar.MINUTE, 1);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
stmt.setDate(1, new java.sql.Date(cal.getTimeInMillis()));

Upvotes: 11

James Jithin
James Jithin

Reputation: 10555

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

Upvotes: 35

Related Questions