gpt4 book ai didi

Java:生成一个范围内的随机日期(范围从当前日期/时间到随机的 future 日期(例如,从当前日期/时间开始的 5-10 天)

转载 作者:行者123 更新时间:2023-12-02 09:44:21 39 4
gpt4 key购买 nike

这里是Java初学者。经过谷歌搜索和研究,这是我认为生成当前日期/时间的最佳方法:

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
  1. 如何将上述当前日期/时间放入变量中?
  2. 如何从当前日期/时间生成随机的 future 日期(例如,随机范围可以是 5 - 10 天),这意味着我没有固定的 future 日期。
  3. 如何将 future 日期存储到变量中?

旁注:为什么我问问题 1 和 3,因为我可以使用存储两个日期的变量进行比较和评估(在 if-else block 中使用)

非常感谢您的帮助!

最佳答案

您可以使用LocalDateTime 相反:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

class Main {
public static void main(String[] args) {
// Declare DateTimeFormatter with desired format.
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(
"yyyy/MM/dd HH:mm:ss");

// Save current LocalDateTime into a variable.
LocalDateTime localDateTime = LocalDateTime.now();

// Format LocalDateTime into a String variable and print.
String formattedLocalDateTime = localDateTime.format(dateTimeFormatter);
System.out.println("Current Date: " + formattedLocalDateTime);

// Get a random amount of days between 5 and 10.
Random random = new Random();
int randomAmountOfDays = random.nextInt(10 - 5 + 1) + 5;
System.out.println("Random amount of days: " + randomAmountOfDays);

// Add randomAmountOfDays to the LocalDateTime variable we defined
// earlier and store it into a new variable.
LocalDateTime futureLocalDateTime = localDateTime.plusDays(
randomAmountOfDays);

// Format new LocalDateTime variable into a String variable and print.
String formattedFutureLocalDateTime = futureLocalDateTime.format(
dateTimeFormatter);
System.out.println("Date " + randomAmountOfDays + " days in future: "
+ formattedFutureLocalDateTime);
}
}

示例输出:

Current Date: 2017/11/22 20:41:03
Random amount of days: 7
Date 7 days in future: 2017/11/29 20:41:03

关于Java:生成一个范围内的随机日期(范围从当前日期/时间到随机的 future 日期(例如,从当前日期/时间开始的 5-10 天),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47443220/

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