Search code examples
javaunix-timestamp

Fetching UNIX epoch time in java


I was trying to fetch the current time in UTC in Java and came across this post: Getting "unixtime" in Java

I checked out that all solutions

  1. new Date().getTime()
  2. System.currentTimeMillis()
  3. Instant.now().toEpochMillis()

return the same value. I wished to know if there is any difference between the three of them. If so then what?


Solution

  • There is no difference. This is just the result of the evolution of the date API over the years. There is now more than one way to do this.

    As far as just getting epoch milliseconds, all three are fine. Things get more complicated as soon as formatting, calendars, timezones, durations and the like become involved.