Reputation: 431
I have with me an epoch time, which i would like to convert to an sql timestamp. I can extract the actual time from the epoch using this code :
String time = "1351504294";
long t = Long.parseLong(time);
Timestamp ts = new Timestamp(t*1000);
The output I'm getting is : 2012-10-29 09:58:50.0
.
But when i try to insert this into a table, it shows error because of the millisecond part, '09:58:50.0'. How can I remove the millisecond part from the timestamp?
Upvotes: 5
Views: 31285
Reputation: 17649
If you are adding the Timestamp
directly to the SQL statement then Java is calling the toString()
function wich always outputs the format yyyy-mm-dd hh:mm:ss.fffffffff
. There is nothing that you could do to the Timestamp
object that would eliminate the nanoseconds part.
If you want just the yyyy-MM-dd hh:mm:ss
portion you could either do:
Timestamp ts = new Timestamp(t*1000);
String s = ts.toString().split('\\.')[0];
Or you could use SimpleDateFormat
:
Timestamp ts = new Timestamp(t*1000);
String s = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(ts);
Upvotes: 8
Reputation: 33544
Try it this way....
public class Time {
public static void main(String[] args){
String time = "1351504294";
long t = Long.parseLong(time);
Timestamp ts = new Timestamp(t*1000);
String date = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss").format(ts);
System.out.println(date);
}
}
Upvotes: 0