在Java中生成随机日期时间(约达时间) [英] Generating Random Date time in java (joda time)

查看:1417
本文介绍了在Java中生成随机日期时间(约达时间)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能使用Jodatime生成随机日期时间,使得日期时间的格式为yyyy-MM-dd HH:MM:SS,并且应该能够生成两个随机日期时间,其中Date2减去Date1会大于2分钟但不到60分钟.请提出一些方法.

Is it possible to generate a random datetime using Jodatime such that the datetime has the format yyyy-MM-dd HH:MM:SS and it should be able to generate two random datetimes where Date2 minus Date1 will be greater than 2 minutes but less than 60minutes. Please suggest some method.

推荐答案

这严格遵循您的要求(更正的格式除外).

This follows quite strictly what you asked for (except for the corrected format).

Random random = new Random();

DateTime startTime = new DateTime(random.nextLong()).withMillisOfSecond(0);

Minutes minimumPeriod = Minutes.TWO;
int minimumPeriodInSeconds = minimumPeriod.toStandardSeconds().getSeconds();
int maximumPeriodInSeconds = Hours.ONE.toStandardSeconds().getSeconds();

Seconds randomPeriod = Seconds.seconds(random.nextInt(maximumPeriodInSeconds - minimumPeriodInSeconds));
DateTime endTime = startTime.plus(minimumPeriod).plus(randomPeriod);

DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

System.out.println(dateTimeFormatter.print(startTime));
System.out.println(dateTimeFormatter.print(endTime));

如果运行此命令,您会注意到多年来您将获得令人发指的值,但这仅仅是在DateTime的整个可能范围(或该日期的Date)上生成随机DateTime的结果.但是,如果需要,可以将结束时间限制在一定范围内的相同技术也可以应用于开始时间.

If you run this, you'll note that you'll get outrageous values for years, but that's simply the consequence of generating a random DateTime over the entire possible range of DateTime (or Date for that matter). But the same technique of limiting the end time to a certain range can be applied to the start time if you want.

这篇关于在Java中生成随机日期时间(约达时间)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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