Java 使用joda时间播种,然后比较

Java 使用joda时间播种,然后比较,java,datetime,jodatime,Java,Datetime,Jodatime,我正在尝试为Joda Time创建一个种子点。我试图实现的是,我将在Joda Time中提供一个种子datetime,这将生成两个不同的随机datetime,使得datetime1早于datetime2,并且该datetime将仅为种子点的特定小时生成值 e、 g 时间从一个DB接收,日期由用户选择。我需要两次随机生成的指定格式 您可以看到,只有分钟和秒会发生更改,其他内容不会被修改 这可能吗?如何实现这一点?下面的代码应该满足您的要求。如果种子时间中的分钟或秒可能不为零,则应在.parseDa

我正在尝试为Joda Time创建一个种子点。我试图实现的是,我将在Joda Time中提供一个种子
datetime
,这将生成两个不同的随机
datetime
,使得
datetime1
早于
datetime2
,并且该
datetime
将仅为种子点的特定小时生成值

e、 g

时间从一个DB接收,日期由用户选择。我需要两次随机生成的指定格式 您可以看到,只有分钟和秒会发生更改,其他内容不会被修改


这可能吗?如何实现这一点?

下面的代码应该满足您的要求。如果种子时间中的分钟或秒可能不为零,则应在
.parseDateTime(inputDateTime)
方法调用之后添加

import java.util.Random;
导入org.joda.time.DateTime;
导入org.joda.time.format.DateTimeFormat;
导入org.joda.time.format.DateTimeFormatter;
公共课随机时间{
DateTimeFormatter inputFormat=DateTimeFormat.forPattern(“HH:mm:ss yyyy-mm-dd”);
DateTimeFormatter outputFormat=DateTimeFormat.forPattern(“yyyy-MM-dd HH:MM:ss”);
public TwoRandomTimes getRandomTimesFromSeed(字符串inputDateTime){
DateTime种子=inputFormat.parseDateTime(inputDateTime);
随机=新随机();
int seconds1=random.nextInt(3600);
int seconds2=random.nextInt(3600-seconds1);
DateTime time1=新的日期时间(种子).plusSeconds(秒1);
DateTime time2=新的DateTime(时间1).plusSeconds(秒2);
返回新的TwoRandomTimes(时间1,时间2);
}
公开课两次{
公开最终日期时间1;
公开最终日期时间2;
private TwoRandomTimes(日期时间时间1、日期时间时间2){
随机数1=时间1;
随机数2=时间2;
}
@凌驾
公共字符串toString(){
返回“Random1-”+outputFormat.print(Random1)+“\nRandom2-”+outputFormat.print(random2);
}
}
公共静态void main(字符串[]args){
RandomTime rt=新的RandomTime();
系统输出打印LN(rt.getRandomTimesFromSeed(“18:00:00 2013-02-13”);
}
}

在这个解中,第一个随机时间确实被用作第二个随机时间的下限。另一种解决方案是只获取两个随机日期,然后对它们进行排序。

我可能会选择以下方法:

final Random r = new Random();
final DateTime suppliedDate = new DateTime();
final int minute = r.nextInt(60);
final int second = r.nextInt(60);

final DateTime date1 = new DateTime(suppliedDate).withMinuteOfHour(minute).withSecondOfMinute(second);
final DateTime date2 = new DateTime(suppliedDate).withMinuteOfHour(minute + r.nextInt(60 - minute)).withSecondOfMinute(second + r.nextInt(60 - second));

假设
suppliedDate
是数据库中的日期。然后根据种子时间生成两个随机分秒的新时间。你还可以通过改变计算出的随机数的界限来保证第二次是在第一次之后。

难以置信的工作,谢谢你,伙计。我从来没有想过通过减去第二次1来获得时间2。非常感谢。@chettyharish,我的荣幸。:)只需检查实现中是否存在拐角情况,然后逐个检查错误。例如,随机时间可能是相同的,特别是如果第一次是18:59:59。
final Random r = new Random();
final DateTime suppliedDate = new DateTime();
final int minute = r.nextInt(60);
final int second = r.nextInt(60);

final DateTime date1 = new DateTime(suppliedDate).withMinuteOfHour(minute).withSecondOfMinute(second);
final DateTime date2 = new DateTime(suppliedDate).withMinuteOfHour(minute + r.nextInt(60 - minute)).withSecondOfMinute(second + r.nextInt(60 - second));