我想生成一个随机时间戳并为其添加一个随机增量以生成第二个时间戳。这可能吗?
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中生成随机时间戳?
发布评论