1

I'm a little confused using the DateTime related class for Java SE 7 and 8 API's, for displaying the current time, I'm reviewing the multiple ways for get the system's current datetime.

My question is: Which one is more accurate for displaying time in millis?

Next is the code snippet, I'm using Java 8 for the reviewing.

import java.time.Instant;
import java.util.Calendar;
import java.util.Date;

public class CurrentTimeValidationDemo {
    public static void main(String[] args) {
        Instant now = Instant.now();
        Calendar calendar=Calendar.getInstance();
        Date currDate = new Date();
        System.out.println("new Date().getTime() = "+currDate.getTime());
        System.out.println("System.currentTimeMillis() = "+System.currentTimeMillis());
        System.out.println("Instant.now().toEpochMilli() = "+now.toEpochMilli());
        System.out.println("Calendar.getInstance().getTimeInMillis() = "+calendar.getTimeInMillis());
        System.out.println("Calendar.getInstance().getTime().getTime() = "+calendar.getTime().getTime());
    }
}
kukkuz
  • 41,512
  • 6
  • 59
  • 95
Marlon López
  • 460
  • 8
  • 21
  • 3
    Define "more accurate". Very related http://stackoverflow.com/questions/368094/system-currenttimemillis-vs-new-date-vs-calendar-getinstance-gettime Note that they won't necessarily print the same thing, `Instant.now` doesn't take timezone or DST of your machine into account. – Tunaki Nov 28 '16 at 15:47
  • 1
    See also my [SO-post](http://stackoverflow.com/a/33478391/2491410) about enhanced resolution in Java-9. – Meno Hochschild Nov 28 '16 at 15:56
  • There will be slight difference in Nano seconds. – Jobin Nov 28 '16 at 15:57

1 Answers1

1

All the functions that you used in your example return the same value (if launched in the same millisecond) none of them is more accurate.

Once of them is not creating any object, so if you need only to know the current milliseconds since 1/1/1970 use

System.currentTimeMillis()

Instead if you need to have also the equivalent object to store that value or to make additional operations use the object that you need.

For example if you need to pass this value to a function accepting a java.util.Date use java.util.Date (and so on).

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • 3
    @Tunaki The expression `Instant.now()` finally delegates to `System.currentTimeMillis()` in Java-8. Just study the source code. And the latter expression does not use DST, too. The same can be said for the expression `new Date()`. – Meno Hochschild Nov 28 '16 at 16:02
  • 1
    @Meno Hmm yes you're right. It seems I was confused about printing the dates directly. – Tunaki Nov 28 '16 at 16:05
  • 1
    @Tunaki Yes, - about `java.util.Date` - `date.toString()` can be extremely confusing. Better take its method `date.getTime()` to see its real state. – Meno Hochschild Nov 28 '16 at 16:08