Search code examples
javatimesimpledateformatepoch

Java time since the epoch


In Java, how can I print out the time since the epoch given in seconds and nanoseconds in the following 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.


Solution

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