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

JavaSqlCalendar

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

You might also want to look at the javadoc.

Solution 3 - Java

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

Solution 4 - Java

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()));

Solution 5 - Java

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

Solution 6 - Java

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

Solution 7 - Java

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

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

Solution 8 - Java

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/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - JavaJimView Answer on Stackoverflow
Solution 2 - JavaKurt Du BoisView Answer on Stackoverflow
Solution 3 - JavaJames JithinView Answer on Stackoverflow
Solution 4 - JavarebeliagamerView Answer on Stackoverflow
Solution 5 - JavaDavid OphiuchusView Answer on Stackoverflow
Solution 6 - JavaSteve PitchersView Answer on Stackoverflow
Solution 7 - JavaVictor MartinView Answer on Stackoverflow
Solution 8 - JavaOritView Answer on Stackoverflow