5

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?

0

2 Answers 2

7

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);
4
  • That worked like charm. I used the second one. 1000 thanks :))
    – sree127
    Oct 29, 2012 at 5:19
  • 2
    ..of which, on my hardware, the former takes roughly 0.9µs and the latter 3.6µs :)
    – phil294
    Mar 27, 2015 at 23:52
  • 1
    Your "yyyy-mm-dd" text should be "yyyy-MM-dd"
    – Chad
    Jul 3, 2015 at 20:55
  • Thanks. I tried ts.toString().split('.') before stumbling on your answer. Does anyone know why splitting the timestamp string only works with \\. but not .. I understand that `\` is sometimes used for escaping but this doesn't help me understand it's use here.
    – Dru
    Aug 4, 2016 at 15:22
0

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);
    }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.