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

前端 未结 8 2320
栀梦
栀梦 2020-12-14 05:40
Calendar cal;
String sql = \"INSERT INTO ttable (dt) values (?);\"
//dt is a dateTime field in ttable

PreparedStatement stmt = connection.prepareStatement(sql);

st         


        
相关标签:
8条回答
  • 2020-12-14 05:53

    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/

    0 讨论(0)
  • 2020-12-14 05:59

    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.

    0 讨论(0)
  • 2020-12-14 06:01

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

    You might also want to look at the javadoc.

    0 讨论(0)
  • 2020-12-14 06:03

    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);
    
    0 讨论(0)
  • 2020-12-14 06:06

    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()));
    
    0 讨论(0)
  • 2020-12-14 06:12

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

    0 讨论(0)
提交回复
热议问题