15

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.

Sufian
  • 6,405
  • 16
  • 66
  • 120
user1585643
  • 211
  • 1
  • 2
  • 9
  • See this [question](http://stackoverflow.com/questions/263376/java-util-calendar-milliseconds-since-jan-1-1970), you should be able to modify it for your needs – ProfessionalAmateur Aug 08 '12 at 18:49

6 Answers6

27

Use this and divide by 1000

long epoch = System.currentTimeMillis();

System.out.println("Epoch : " + (epoch / 1000));
ProfessionalAmateur
  • 4,447
  • 9
  • 46
  • 63
  • 3
    This displays **current** seconds since epoch. It's off topic. – Adam Zalcman Aug 08 '12 at 19:11
  • 1
    Yep, I completely misread the question for some reason, thought he was asking for seconds. – ProfessionalAmateur Aug 08 '12 at 19:34
  • 12
    Completely agree that is it off topic, but it is what I was searching for, and one of first results was here. My query was java epoch time and my goal was to get the current epoch time – Paul Jan 09 '14 at 14:37
10

tl;dr

    Instant                        // Represent a moment in UTC.
    .ofEpochSecond( mnSeconds )   // Determine a moment from a count of whole seconds since the Unix epoch of the first moment of 1970 in UTC (1970-01-01T00:00Z). 
    .plusNanos( mnNanoseconds )    // Add on a fractional second as a count of nanoseconds. Returns another `Instant` object, per Immutable Objects pattern.
    .toString()                    // Generate text representing this `Instant` object in standard ISO 8601 format.
    .replace( "T" , " " )          // Replace the `T` in the middle with a SPACE. 
    .replace "Z" , "" )            // Remove the `Z` on the end (indicating UTC).

java.time

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, java.text.SimpleDateFormat, java.sql.Date, and more. The Joda-Time team also advises migration to java.time.

Instant

The Instant class represents a moment on the timeline in UTC with a resolution up to nanoseconds.

long mnSeconds = … ;
long mnNanoseconds = … ;

Instant instant = Instant.ofEpochSecond( mnSeconds ).plusNanos( mnNanoseconds );

Or pass both numbers to the of, as two arguments. Different syntax, same result.

Instant instant = Instant.ofEpochSecond( mnSeconds , mnNanoseconds );

To get a String representing this date-time value, call Instant::toString.

String output = instant.toString();

You will get a value such as 2011-12-03T10:15:30.987654321Z, standard ISO 8601 format. Replace the T with a SPACE if you wish. For other formats, search Stack Overflow to learn about DateTimeFormatter.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
9

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));
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • That's what I would do except that the format he wants it in doesn't output more than milliseconds (.SSS) so that last String.format() call is kind of unwanted. – Fredrik Aug 08 '12 at 18:57
  • Great answer - and FAST! Thanks. Fredrik, it does do ms - that is what the + String.format("%09d", mnNanoseconds); part does! – user1585643 Aug 08 '12 at 21:57
  • @user1585643 you missed my point. That part does milliseconds AND micros and nanos. The format string in the question only has milliseconds (three decimals) so I assumed that is what you wanted not nine decimals. – Fredrik Aug 09 '12 at 05:48
  • @user1585643 Its not clear in the question whether you wanted milli-seconds, micro-seconds or nano-seconds. These are not the same thing at all. BTW I tend to record and display micro-seconds in my systems as getting anything more accurate than this is very hard. – Peter Lawrey Aug 09 '12 at 07:05
1

java.util.Date class has a constructor which accepts the epoch milliSeconds.

Check the java doc and try to make use of it.

onkar
  • 4,427
  • 10
  • 52
  • 89
sundar
  • 1,760
  • 12
  • 28
1

It depends a bit on the values of you mnSeconds and mnNanoseconds but all you need to do with a formatter like that one (which has millisecond precision) is to create a java.util.Date. If mnNanoseconds is the number of nanoseconds on top of your mnSeconds, I would assume it to be something like

Date d = new Date(mnSeconds*1000+mnNanosecods/1000000)

Then it is a matter of formatting it with your formatter before printing it.

Fredrik
  • 5,759
  • 2
  • 26
  • 32
0

You can use

new java.util.Date(mnSeconds);

and then SimpleDateFormat to format your output.

Nanoseconds are not supported by Date. You have to manually add Nanoseconds or use some framework (is there one?).

John Smith
  • 2,282
  • 1
  • 14
  • 22
  • The OP only requires milliseconds and [`java.util.Date`](http://docs.oracle.com/javase/7/docs/api/java/util/Date.html) does support this. No need for extra frameworks. – Adam Zalcman Aug 08 '12 at 19:12