Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 248
Shitu Avatar asked Apr 04 '14 08:04

Shitu


People also ask

What is the format of Java sql timestamp?

Formats a timestamp in JDBC timestamp escape format. yyyy-mm-dd hh:mm:ss.

Does Java sql date have time?

Its main purpose is to represent SQL DATE, which keeps years, months and days. No time data is kept. In fact, the date is stored as milliseconds since the 1st of January 1970 00:00:00 GMT and the time part is normalized, i.e. set to zero. Basically, it's a wrapper around java.


4 Answers

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
like image 81
janos Avatar answered Oct 19 '22 12:10

janos


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));
like image 15
Markus Avatar answered Oct 19 '22 10:10

Markus


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
like image 8
RaceBase Avatar answered Oct 19 '22 11:10

RaceBase


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

like image 3
Miron Balcerzak Avatar answered Oct 19 '22 10:10

Miron Balcerzak