gpt4 book ai didi

java - 使用 joda time 播种然后比较

转载 作者:行者123 更新时间:2023-11-30 11:35:58 25 4
gpt4 key购买 nike

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

例如

time- 18:00:00  followed by date-2013-02-13

Random1 - 2013-02-13 18:05:24

Random2 - 2013-02-13 18:48:22

时间从一个数据库接收,日期由用户选择。我需要指定格式随机生成的两次可以看到只有分秒会发生变化,其他的都没有变化。

这可能吗?我怎样才能做到这一点?

最佳答案

下面的代码应该做你想做的。如果种子时间中的分钟或秒可能不为零,则应添加 .withMinuteOfHour(0) .withSecondOfMinute(0).parseDateTime(inputDateTime) 方法调用之后。

import java.util.Random;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class RandomTime {

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

public TwoRandomTimes getRandomTimesFromSeed(String inputDateTime) {
DateTime seed = inputFormat.parseDateTime(inputDateTime);
Random random = new Random();
int seconds1 = random.nextInt(3600);
int seconds2 = random.nextInt(3600 - seconds1);

DateTime time1 = new DateTime(seed).plusSeconds(seconds1);
DateTime time2 = new DateTime(time1).plusSeconds(seconds2);
return new TwoRandomTimes(time1, time2);
}

public class TwoRandomTimes {
public final DateTime random1;
public final DateTime random2;

private TwoRandomTimes(DateTime time1, DateTime time2) {
random1 = time1;
random2 = time2;
}

@Override
public String toString() {
return "Random1 - " + outputFormat.print(random1) + "\nRandom2 - " + outputFormat.print(random2);
}
}

public static void main(String[] args) {
RandomTime rt = new RandomTime();
System.out.println(rt.getRandomTimesFromSeed("18:00:00 2013-02-13"));
}
}

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

关于java - 使用 joda time 播种然后比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14791280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com