简体   繁体   English

为什么date.toString()两次打印相同的结果

[英]Why date.toString() twice to print the same result

When I call the method date.toString() twice, I have the same result, even though there is a two second interval. 当我两次调用方法date.toString() ,即使有两秒钟的间隔,我也会得到相同的结果。 I think the second time should be 2s more than first time. 我认为第二次应该比第一次多2秒。

Program for example: 程序例如:

Date date = new Date();
System.out.println(date.toString());
System.out.println("----------");
Thread.sleep(2000);
System.out.println(date.toString());

The output is 输出是

Sat Oct 17 17:54:39 CST 2015
----------
Sat Oct 17 17:54:39 CST 2015

Quoting the Javadoc of the constructor of Date (emphasis mine): 引用Date的构造函数的Javadoc(重点是我的):

Allocates a Date object and initializes it so that it represents the time at which it was allocated , measured to the nearest millisecond. 分配一个Date对象并对其进行初始化,以便它表示分配该对象的时间以最近的毫秒为单位)。

As such, the Date that is printed is the date when the object was created. 这样, Date即打印是当创建对象的时间。 Since you are printing the same Date object, it will be the same output. 由于您正在打印相同的Date对象,因此它将是相同的输出。

Date date = new Date();
System.out.println(date.toString());
System.out.println("----------");
Thread.sleep(2000);
date = new Date(); // instantiate a new Date here
System.out.println(date.toString());

Output on my machine: 我的机器上的输出:

Sat Oct 17 12:09:16 CEST 2015
----------
Sat Oct 17 12:09:18 CEST 2015

try this... 尝试这个...

Date date = new Date();
System.out.println(date.toString());
System.out.println("----------");
Thread.sleep(2000);
date = new Date();
System.out.println(date.toString());

just initiate again the "date" before print for the second time 只需在第二次打印之前再次启动“日期”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM