0

I'm trying to fetch Unix Timestamp value using below snippet but sometimes the value get corrupted like 11030 or 810 something like random number we don,t get actual date

public static int getUnixTimeStamp() {

  Date date = new Date();

  return (int) (date.getTime() / 1000);

}
dariosicily
  • 4,239
  • 2
  • 11
  • 17
  • Weird. Looking at your code I cannot explain. I also cannot reproduce on my desktop Java. It’s better to use `long` than `int` to avoid [the Year 2038 problem](https://en.wikipedia.org/wiki/Year_2038_problem). – Ole V.V. Feb 27 '21 at 16:00

2 Answers2

2

java.time

I cannot tell you whether it alleviates your problem. In you insist on having the year 2038 problem, this how I would prefer to write the method:

public static int getUnixTimeStamp() {
    Instant now = Instant.now();
    return Math.toIntExact(now.getEpochSecond());
}

The method just returned 1 614 441 874. I am using java.time, the modern Java date and time API, which is rock solid, so I should say that you have a chance. Other advantages of the code are (1) there is no conversion from milliseconds to seconds (2) in 2038 the code will stop working rather than start giving surprising incorrect results.

Link: Year 2038 problem

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
2

Instead of performing the calculations yourself, let Java do it for you.

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) {
        long millis = new Date().getTime();
        System.out.println(millis);
        long seconds = TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS);
        System.out.println(seconds);
    }
}

Output:

1614443708365
1614443708

I also recommend you use long instead of int variable to store seconds.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110