Reputation: 3405
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
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
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
Reputation: 7374
stmt.setDate(1, new java.sql.Date(cal.getTime().getTime()));
Upvotes: 4
Reputation: 7665
Did you try cal.getTime()
? This gets the date representation.
You might also want to look at the javadoc.
Upvotes: 35
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
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
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
Reputation: 10555
Use stmt.setDate(1, new java.sql.Date(cal.getTimeInMillis()))
Upvotes: 35