4

Given a timestamp in milliseconds, i want to convert it to an timestamp in seconds.

I want to do it in java

Stefanos13
  • 129
  • 1
  • 1
  • 11

2 Answers2

14

You can use TimeUnit to convert times, like this:

public static void main(String[] args) {
    long timestampMillis = System.currentTimeMillis();
    long timestampSeconds = TimeUnit.MILLISECONDS.toSeconds(timestampMillis);
    System.out.println("Seconds: " + timestampSeconds);
}

The advantage with this, compared to simply dividing by 1000, is that you can easily adjust it to other units (days, hours, minutes) by calling other toXXX methods.

duckstep
  • 1,148
  • 8
  • 17
7

You need to simply divide the milliseconds value by 1000 and you will get the value in seconds.

Something like this:

int seconds = (int) (milliseconds / 1000) ;
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331