gpt4 book ai didi

java - 为每次迭代生成不同的日期

转载 作者:行者123 更新时间:2023-12-01 07:18:58 25 4
gpt4 key购买 nike

这里需要在 for 循环的每次迭代中为 Date 生成不同的值。

使用 currentTimeMillis 没有帮助,因为它给出了相同的时间,但 nanoTime 给出了错误的日期。

    for (int i = 0; i < 10; i++) {
System.out.println(new Date(System.currentTimeMillis()));
}

for (int i = 0; i < 10; i++) {
System.out.println(new Date(System.nanoTime()));
}
<小时/>
Mon Oct 30 19:33:43 IST 2017
Mon Oct 30 19:33:43 IST 2017
Mon Oct 30 19:33:43 IST 2017
Mon Oct 30 19:33:43 IST 2017
Mon Oct 30 19:33:43 IST 2017
Mon Oct 30 19:33:43 IST 2017
Mon Oct 30 19:33:43 IST 2017
Mon Oct 30 19:33:43 IST 2017
Mon Oct 30 19:33:43 IST 2017
Mon Oct 30 19:33:43 IST 2017
<小时/>
Tue Feb 09 09:56:54 IST 2292
Tue Feb 09 09:57:39 IST 2292
Tue Feb 09 09:58:10 IST 2292
Tue Feb 09 09:58:50 IST 2292
Tue Feb 09 09:59:24 IST 2292
Tue Feb 09 09:59:53 IST 2292
Tue Feb 09 10:00:29 IST 2292
Tue Feb 09 10:00:59 IST 2292
Tue Feb 09 10:01:37 IST 2292
Tue Feb 09 10:02:18 IST 2292

更新:需要为每次迭代生成不同的时间戳,因为在 cassandra 数据库中,不同的记录需要具有唯一的时间戳。否则它们会互相覆盖。另外,时间不应该是假的,因为在 for 循环中添加第二秒可以解决问题,但这是假时间。不幸的是,添加 sleep 不是一个选项,因为代码需要尽快添加记录并退出

最佳答案

首先要注意,纳米比毫提供更多的值,并且您传递的是纳秒值而不是毫秒,因此会出现奇怪的结果。

什么Date(long date)构造函数期望

date - the milliseconds since January 1, 1970, 00:00:00 GMT.

nanoTime 返回什么

Returns the current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds.

nanoTime与 Date() 完全无关。它的设计和实现是为了解决不同的目的。

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.

<小时/>

Here needed to generate different values for Date in each iteration of for loop.

也许您可以尝试通过添加i值来将时间(以分钟/天为单位)添加到当前日期?

关于java - 为每次迭代生成不同的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47017246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com