Converting java date to Sql timestamp

177,250

Solution 1

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

Solution 2

Take a look at SimpleDateFormat:

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

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
System.out.println(sdf.format(sq));

Solution 3

The problem is with the way you are printing the Time data

java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());
System.out.println(sa); //this will print the milliseconds as the toString() has been written in that format

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(timestamp)); //this will print without ms

Solution 4

I suggest using DateUtils from apache.commons library.

long millis = DateUtils.truncate(utilDate, Calendar.MILLISECOND).getTime();
java.sql.Timestamp sq = new java.sql.Timestamp(millis );

Edit: Fixed Calendar.MILISECOND to Calendar.MILLISECOND

Solution 5

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);

This gives me the following output:

 utilDate:Fri Apr 04 12:07:37 MSK 2014
 sqlDate:2014-04-04
Share:
177,250
Shitu
Author by

Shitu

Software Engineer

Updated on January 03, 2020

Comments

  • Shitu
    Shitu over 4 years

    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?

  • Jon Skeet
    Jon Skeet about 10 years
    The OP is interested in storing the data to a database - that doesn't require a text conversion at all. The question is unclear, basically - it's not obvious whether the OP doesn't want to store milliseconds or doesn't want to render them.
  • Njeru Cyrus
    Njeru Cyrus about 6 years
    please change Calender.MILISECONDS to Calendar.MILLISECOND that is the correct property