Java current time different values in api

强颜欢笑 提交于 2021-02-16 14:57:50

问题


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());
    }
}

回答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).



来源:https://stackoverflow.com/questions/40848243/java-current-time-different-values-in-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!