0

I wanted to get the current time in seconds. I found 3 approaches. But confused which one will be the best option.

long usingEpochSecond = Instant.now().getEpochSecond();
long usingDate1 = TimeUnit.MILLISECONDS.toSeconds(new Date().getTime());
long usingDate2 = new Date().getTime()/1000

Which one is the best solution? Is there an even better option?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
AJ007
  • 189
  • 3
  • 13
  • 3
    Only the first one uses the [java.time](https://docs.oracle.com/javase/tutorial/datetime/index.html) package and hence is the recommended way. – Abra Aug 04 '21 at 12:24
  • 2
    Easy: The first one because it does not involve an outdated API (`java.util`). – deHaar Aug 04 '21 at 12:24
  • Great. thanks @Abra for the quick response :) – AJ007 Aug 04 '21 at 12:25
  • Thanks @deHaar for quick response – AJ007 Aug 04 '21 at 12:26
  • 2
    `TimeUnit.MILLISECONDS.toSeconds(System.currentTimemills())` is a valid answer too - there’s no real reason to create an `Instant` just to throw it away. – Boris the Spider Aug 04 '21 at 12:27
  • 1
    Sure, all the answers are valid, but OP asked for the *best* solution, and every answer to it is somehow opinion-based ;-) – deHaar Aug 04 '21 at 12:33
  • Thanks @BoristheSpider. it is a valid point too. – AJ007 Aug 04 '21 at 12:38
  • In any case I recommend you don’t use the `Date` class. It is poorly designed and long outdated. Apart from that use what will be least surprising to those reading your code. You may know them better than I do. – Ole V.V. Aug 04 '21 at 17:46

0 Answers0