java获取随机时间,在Java中生成随机日期时间(约达时间)

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));

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值