2

Im trying to convert milliseconds to seconds with System.currentTimeMillis();

System.out.println((int) System.currentTimeMillis() / 1000);

The output is 730750 and increasing by 1. How can i get seconds starting from 0?

**UPDATE: Now i understand the problem and thank you for answering it.

Mert Karakas
  • 178
  • 1
  • 4
  • 22
  • 1
    Define "from 0"; what does zero mean in this case? Are you trying to determine an elasped time, for example? – Paul Richter Dec 08 '14 at 20:38
  • 1
    I am not sure what you are trying to do, but casting to `int` is definitely a problem. You are truncating that long before dividing which gives you a number that is incorrect for any question you might ask. Besides, `System.out.println()` is overloaded for all primitive types. –  Dec 08 '14 at 20:41

4 Answers4

5

System.currentTimeMillis() is from January 1, 1970. It will take today's time and subtract it from midnight January 1, 1970. That is why it is so many seconds.

brso05
  • 13,142
  • 2
  • 21
  • 40
4

From the Javadocs of System.currentTimeMillis():

Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

To start from zero, you need to define a start time. Then you can print the time elapsed after that start time.

long startTime = System.currentTimeMillis();
...
System.out.println((System.currentTimeMillis() - startTime) / 1000);
M A
  • 71,713
  • 13
  • 134
  • 174
3

Since the time is based on the epoch 1.1.1970, you need to base it to the current time.

long start = System.currentTimeMillis();
System.out.println((System.currentTimeMillis() - start) / 1000l);
Thomas Jungblut
  • 20,854
  • 6
  • 68
  • 91
3

If you want elapsed time, you can store the start time and then later check the current time. Ex.

int startTimeSeconds = (int) System.currentTimeMillis() / 1000;
// do stuff
System.out.println("Time elapsed: ");
System.out.println(((int) System.currentTimeMillis() / 1000) - startTimeSeconds);
dave
  • 1,607
  • 3
  • 16
  • 20