58

How to convert System.currentTimeMillis(); to seconds?

long start6=System.currentTimeMillis();
System.out.println(counter.countPrimes(100000000)+" for "+start6);

The console shows me 5761455 for 1307816001290. I can't read how many seconds that is.

Any help?

2
  • 3
    long s = System.currentTimeMilis() / 1000L
    – SARose
    Jan 7, 2015 at 20:18
  • 1
    Try Instant will more clearly: long s = Instant.now().getEpochSecond();
    – free斩
    Jan 5, 2017 at 7:42

9 Answers 9

101

TimeUnit

Use the TimeUnit enum built into Java 5 and later.

long timeMillis = System.currentTimeMillis();
long timeSeconds = TimeUnit.MILLISECONDS.toSeconds(timeMillis);
4
  • 5
    Wow, havn't heard about the TimeUnit thing before.
    – chakrit
    Jul 9, 2013 at 4:53
  • seems like not working for me :O can you please help out?It still give me the result same as System.currentTimeMillis() Feb 25, 2015 at 16:07
  • Haven't heard of this method, nice. But you loose precision when 1500 msecs are converted to 1 sec, not that nice. Mar 17, 2016 at 13:06
  • 1
    @PeterClause Of course you lose resolution going from fractional seconds to whole seconds. What else would you expect? Jan 22, 2017 at 0:19
80
long start = System.currentTimeMillis();
counter.countPrimes(1000000);
long end = System.currentTimeMillis();

System.out.println("Took : " + ((end - start) / 1000));

UPDATE

An even more accurate solution would be:

final long start = System.nanoTime();
counter.countPrimes(1000000);
final long end = System.nanoTime();

System.out.println("Took: " + ((end - start) / 1000000) + "ms");
System.out.println("Took: " + (end - start)/ 1000000000 + " seconds");
5
  • 3
    The time in nanoseconds needs to be divided by 10^9 (1000000000) to display as seconds. Can't edit the answer as I only have to insert 3 characters instead of the 6 required. :]
    – Lilienthal
    May 2, 2013 at 12:37
  • Sorry, wanted it to be ms instead of s. Thanks for spotting it. May 2, 2013 at 13:00
  • 7
    Why would someone want to use nanoTime() instead of currentTimeMillis() when the result is needed in seconds?
    – Uooo
    May 2, 2013 at 13:04
  • I, uh, didn't consider that. It was still good to learn of nanoTime's existence for me as it would be fairly more useful in scenarios where many large volumes of operations need to be timed or logged.
    – Lilienthal
    May 2, 2013 at 13:22
  • 1
    @Uooo currentTimeMillis() is for "wall time", and nanoTime() is high resolution elapsed time. There is a slight difference in them, and their purpose. nanoTime() is not affected by local time settings, clock corrections and such, and the difference of a later to earlier call is guaranteed to never be negative (on the same VM, in the same power cycle). There is no such guarantee for currentTimeMillis(). Use currentTimeMillis() to answer "with current time settings, how much time passed since 1970 jan 1", not "how much more time passed since I last called this function" Apr 19, 2017 at 10:32
15

like so:

(int)(milliseconds / 1000)
10

Java 8 now provides the most concise method to get current Unix Timestamp:

Instant.now().getEpochSecond();
9

From your code it would appear that you are trying to measure how long a computation took (as opposed to trying to figure out what the current time is).

In that case, you need to call currentTimeMillis before and after the computation, take the difference, and divide the result by 1000 to convert milliseconds to seconds.

3

I have written the following code in my last assignment, it may help you:

// A method that converts the nano-seconds to Seconds-Minutes-Hours form
private static String formatTime(long nanoSeconds)
{
    int hours, minutes, remainder, totalSecondsNoFraction;
    double totalSeconds, seconds;


    // Calculating hours, minutes and seconds
    totalSeconds = (double) nanoSeconds / 1000000000.0;
    String s = Double.toString(totalSeconds);
    String [] arr = s.split("\\.");
    totalSecondsNoFraction = Integer.parseInt(arr[0]);
    hours = totalSecondsNoFraction / 3600;
    remainder = totalSecondsNoFraction % 3600;
    minutes = remainder / 60;
    seconds = remainder % 60;
    if(arr[1].contains("E")) seconds = Double.parseDouble("." + arr[1]);
    else seconds += Double.parseDouble("." + arr[1]);


    // Formatting the string that conatins hours, minutes and seconds
    StringBuilder result = new StringBuilder(".");
    String sep = "", nextSep = " and ";
    if(seconds > 0)
    {
        result.insert(0, " seconds").insert(0, seconds);
        sep = nextSep;
        nextSep = ", ";
    }
    if(minutes > 0)
    {
        if(minutes > 1) result.insert(0, sep).insert(0, " minutes").insert(0, minutes);
        else result.insert(0, sep).insert(0, " minute").insert(0, minutes);
        sep = nextSep;
        nextSep = ", ";
    }
    if(hours > 0)
    {
        if(hours > 1) result.insert(0, sep).insert(0, " hours").insert(0, hours);
        else result.insert(0, sep).insert(0, " hour").insert(0, hours);
    }
    return result.toString();
}

Just convert nano-seconds to milli-seconds.

2
TimeUnit.SECONDS.convert(start6, TimeUnit.MILLISECONDS);
2

For conversion of milliseconds to seconds, since 1 second = 10³ milliseconds:

//here m will be in seconds
long m = System.currentTimeMillis()/1000;

//here m will be in minutes
long m = System.currentTimeMillis()/1000/60; //this will give in mins
1
// Convert millis to seconds. This can be simplified a bit,
// but I left it in this form for clarity.
long m = System.currentTimeMillis(); // that's our input
int s = Math.max(
  .18 * (Math.toRadians(m)/Math.PI),
  Math.pow( Math.E, Math.log(m)-Math.log(1000) )
);
System.out.println( "seconds: "+s );
3
  • 4
    What you left in for clarity is quite confusing... maybe you should edit your post and explain it. Oct 3, 2012 at 19:53
  • 2
    That code just divides m by 1000. Doing so with logarithm and radians and exponents was for your reading enjoyment.
    – freeideas
    Aug 21, 2013 at 21:29
  • System.out.println( "seconds: s" ); prints literal 's' Mar 3, 2016 at 3:27

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