user1585643 user1585643 - 4 months ago 10
Java Question

Java time since the epoch

In Java, how do I print out a time since the epoch given in seconds and nanoseconds in the format


java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");



My input is:


long mnSeconds;
long mnNanoseconds;



Where the total of the two is the elapsed time since the epoch 1970-01-01 00:00:00.0.

Answer

You can do this

public static String format(long mnSeconds, long mnNanoseconds) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.");
    return sdf.format(new Date(mnSeconds*1000))
           + String.format("%09d", mnNanoseconds);
}

e.g.

2012-08-08 19:52:21.123456789

if you don't really need any more than milliseconds you can do

public static String format(long mnSeconds, long mnNanoseconds) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    return sdf.format(new Date(mnSeconds*1000 + mnNanoseconds/1000000));
}
Comments