如何在java中生成随机时间戳?

编程入门 行业动态 更新时间:2024-10-27 02:26:25
本文介绍了如何在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中生成随机时间戳?

本文发布于:2023-11-23 14:52:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621849.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间   如何在   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!