Search code examples
javasqldatetimesqldatetime

Converting java date to Sql timestamp


I am trying to insert java.util.Date after converting it to java.sql.Timestamp and I am using the following snippet:

java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());

But this is giving me sq as 2014-04-04 13:30:17.533

Is there any way to get the output without milliseconds?


Solution

  • You can cut off the milliseconds using a Calendar:

    java.util.Date utilDate = new java.util.Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(utilDate);
    cal.set(Calendar.MILLISECOND, 0);
    System.out.println(new java.sql.Timestamp(utilDate.getTime()));
    System.out.println(new java.sql.Timestamp(cal.getTimeInMillis()));
    

    Output:

    2014-04-04 10:10:17.78
    2014-04-04 10:10:17.0