13

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?

Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
SohamC
  • 2,367
  • 6
  • 22
  • 34

1 Answers1

11

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.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • 5
    To be pedantic, the first two return the epoch time in milliseconds, the last one returns it in seconds. System.currentTimeMillis()/1000 will give seconds of course. The third option of course is the most readable. – user1471465 Sep 29 '16 at 10:06
  • 1
    The last one should be `Instant.now().getMillis()` to be in line with everything in milliseconds. – CyberMew Nov 29 '18 at 10:38
  • Actually @CyberMew is `Instant.now().toEpochMilli()`. – Pablo Santa Cruz Aug 16 '19 at 23:53