Java API中的Java当前时间不同值 [英] Java current time different values in api

查看:103
本文介绍了Java API中的Java当前时间不同值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Java SE 7和8 API,使用与DateTime相关的类对我有些困惑,为了显示当前时间,我在审查获取系统当前日期时间的多种方法.

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?

接下来是代码段,我正在使用Java 8进行审核.

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

推荐答案

在示例中使用的所有函数都返回相同的值(如果在同一毫秒内启动),那么它们都不是更准确的.

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.

一旦它们没有创建任何对象,那么如果您只需要知道自1970年1月1日以来使用的当前毫秒数

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.

例如,如果您需要将此值传递给接受java.util.Date的函数,请使用java.util.Date(依此类推).

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

这篇关于Java API中的Java当前时间不同值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆