如何在java中生成随机时间戳? [英] how to generate a random timestamp in java?

查看:605
本文介绍了如何在java中生成随机时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个随机时间戳并为其添加一个随机增量以生成第二个时间戳。这可能吗?

I want to generate a random timestamp and add a random increment to it to generate a second timestamp. is that possible?

如果我传递随机长值来创建时间戳并且我想随机生成那个长值,那么生成此值的约束是什么?例如2012年的时间戳?

If i pass random long values to create a timestamp and i want to randomly generate that long value, what would be the constraints to generate this value to give a timestamp in 2012 for example?

推荐答案

您需要将随机数缩放到特定年份的范围内,并将年份的开头添加为偏移量。一年中的毫秒数从一年变为另一年(闰年有一天,某些年有闰分,依此类推),因此您可以在缩放之前确定范围,如下所示:

You need to scale the random number to be in the range of a specific year, and add the year's beginning as the offset. The number of milliseconds in a year changes from one year to another (leap years have an extra day, certain years have leap minutes, and so on), so you can determine the range before scaling as follows:

long offset = Timestamp.valueOf("2012-01-01 00:00:00").getTime();
long end = Timestamp.valueOf("2013-01-01 00:00:00").getTime();
long diff = end - offset + 1;
Timestamp rand = new Timestamp(offset + (long)(Math.random() * diff));

这篇关于如何在java中生成随机时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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