首页 > 其他分享 >new Date().getTime()和System.currentTimeMillis()获取时间戳的比较

new Date().getTime()和System.currentTimeMillis()获取时间戳的比较

时间:2023-05-24 21:06:35浏览次数:37  
标签:getTime System currentTimeMillis 获取 源码 time Date


最近在优化项目代码,看项目组的代码时,发现了一个有趣的现象,有使用new Date().getTime()来获取时间戳的, 也有使用System.currentTimeMillis()来获取时间戳的,这让我想到,好像我平时写代码也是想起哪种方式就用什么方式写。这两种方式都可以,仔细思考一下,两者应该会有区别的,应该有是最优的方式?

然后就看了看源码,其实解决疑惑最优方式就是看源码,打开java.util.Date的源码可以发现,无参构造函数如下:

/**
     * Allocates a <code>Date</code> object and initializes it so that
     * it represents the time at which it was allocated, measured to the
     * nearest millisecond.
     *
     * @see     java.lang.System#currentTimeMillis()
     */
    public Date() {
        this(System.currentTimeMillis());
    }

    /**
     * Allocates a <code>Date</code> object and initializes it to
     * represent the specified number of milliseconds since the
     * standard base time known as "the epoch", namely January 1,
     * 1970, 00:00:00 GMT.
     *
     * @param   date   the milliseconds since January 1, 1970, 00:00:00 GMT.
     * @see     java.lang.System#currentTimeMillis()
     */
    public Date(long date) {
        fastTime = date;
    }

从源码可以看出,new Date().getTime()其实就是在无参构造里调用了System.currentTimeMillis(),再传入自己的有参构造函数。不难看出,如果只是仅仅获取时间戳,即使是匿名的new Date()对象也会有些许的性能消耗, 从性能提升的角度来看,如果只是仅仅获取时间戳,不考虑时区的影响(时区为什么会有影响),直接调用System.currentTimeMillis()会更好一些。

再来看看System.currentTimeMillis()的源码:

/**
     * Returns the current time in milliseconds.  Note that
     * while the unit of time of the return value is a millisecond,
     * the granularity of the value depends on the underlying
     * operating system and may be larger.  For example, many
     * operating systems measure time in units of tens of
     * milliseconds.
     *
     * <p> See the description of the class <code>Date</code> for
     * a discussion of slight discrepancies that may arise between
     * "computer time" and coordinated universal time (UTC).
     *
     * @return  the difference, measured in milliseconds, between
     *          the current time and midnight, January 1, 1970 UTC.
     * @see     java.util.Date
     */
    public static native long currentTimeMillis();

这是一个本地方法,其时间来源依赖由操作系统为其做了时区的处理,因此获取时间戳,不需要考虑时区的前提下,它是最优选择。

其实, java.util.Date设计来作为格式化时间,以面向对象的方式获取与时间有关的各方面信息,例如:获取年月份、小时、分钟等等比较丰富的信息。而new Date()来获取当前时间更多的是因为我们使用习惯导致经常第一时间想到用它来获取当前时间。

 

扩展:关于获取时间戳另一种方式:

在Java中,还可能见到另外一种获取时间的方式:

Calendar.getInstance().getTimeInMillis()

其实这种方式是速度最慢的,看其源码就会发现,Canlendar是区分时区的,因为要处理时区问题会耗费很多的时间。

 

标签:getTime,System,currentTimeMillis,获取,源码,time,Date
From: https://blog.51cto.com/u_16128050/6342840

相关文章

  • System类
    System类System类代表系统,系统级的很多属性和控制方法都放置在该类的内部。该类位于java.lang包由于该类的构造器是private的,所以无法创建该类的对象,也就是无法实例化该类。其内部的成员变量和成员方法都是static的,所以也可以很方便的进行调用。成员变量System类内部包含in......
  • c#中用System.Diagnostics.Process.Start(Path.GetFullPath(“vlc.exe.lnk“), url);用
    vlc.exe.lnk双击这个文件,能正常打开vlc,但是用System.Diagnostics.Process.Start(Path.GetFullPath("vlc.exe.lnk"),url);没有任何反应。根据常理,不应该出现这个问题。但是现实就是这么魔幻,偏偏有这个问题。根据上面图,根据快捷方式是可以获取到vlc可执行文件的路径的,然后在网上搜索......
  • c#中用System.Diagnostics.Process.Start(Path.GetFullPath(“vlc.exe.lnk“), url);用
    vlc.exe.lnk双击这个文件,能正常打开vlc,但是用System.Diagnostics.Process.Start(Path.GetFullPath("vlc.exe.lnk"),url);没有任何反应。根据常理,不应该出现这个问题。但是现实就是这么魔幻,偏偏有这个问题。根据上面图,根据快捷方式是可以获取到vlc可执行文件的路径的,然后在网上......
  • System.Windows.Forms.TextBox ImeMode只输入数字或者只输入文字快以及捷键ctrl+c ctr
    //设置输入法发编辑模式,例如只输入数字或者只输入文字等等txtPassword.ImeMode=ImeMode.Off;//指示是否启用定义的快捷方式,例如设置快捷键ctrl+cctrl+v是否可用txtPassword.ShortcutsEnabled=false;txtPassword.Password......
  • SystemVerilog for Design Edition 2 Chapter 6
    SystemVerilogforDesignEdition2Chapter6TheVeriloglanguageprovidesageneralpurposeproceduralblock,calledalways,thatisusedtomodelavarietyofhardwaretypesaswellasverificationroutines.Becauseofthegeneralpurposeapplicationof......
  • [hc32f460填坑] SystemCoreClock在进入main后变为0
    我的芯片型号是hc32f460jeua,使用的库为HC32F460_DDL_Rev3.1.0,keil包为HDSC.HC32F460.1.0.10。发现的问题:执行完SystemInit后SystemCoreClock为200000000,一进入mian函数就变为零。原因:__NO_INIT未起作用,__main对SystemCoreClock进行了初始化解决方法:1.把这两个勾上2,将Zero......
  • ahb_system_generator
    0.ahb_system_generatorEnviroment:WSL2ahb_generator要运行AHB系统生成器,必须安装PERL(一般系统自带)和一个名为Tk的GUIPERL模块perl--version //检查perlperl-e"useTk" //检查Tk模块,若未安装会返回错误信息1.perlinstall官网下载Tk模块安装包进入解压......
  • System.Text.Json匿名对象反序列化
    以前就是一直使用Newtonsoft.Json用起来还是挺舒服的。由于JSON的应用越来越广,现在.NETCore都内置了System.Text.Json可以直接对JSON进行操作,不过两个东西的体验依然有点区别。有时候我们会遇到的从第三方传递过来的jsonstring对象,对其进行解析并不需要所有的字段,......
  • UE Build System:Target and Module
    Module是构成Unreal的基本元素,每一个Module封装和实现了一组功能,并且可以供其他的Module使用,整个UnrealEngine就是靠各个Module组合驱动的,连我们创建的游戏项目本身,都是一个单独的Module。那么UE又是怎么创建和构建这这些Module的呢?这是写这篇文章的主要目的,研......
  • MVC4 部署 could not load file or assembly system.web.http.webhost.....出错
    1.确保项目是.net4.0版本 2.如下图标出的部分,确保这个dll引用是项目本地,找到项目下的“引用”,找到对应的引用右键属性,将“复制本地”改为True,这里我们可以在项目下新建一个存入dll的文件夹,将这些dll放在这个文件夹里面,路径引用改为复制本地为True后就自动引用这个文件夹的路......