Java:在范围之间生成一个随机日期(从当前日期/时间到随机的将来日期(例如,从当前日期/时间开始)



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

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

旁注:为什么我问问题1和3,这是因为我可以使用将两个日期存储的变量用于比较和评估目的(用于IF-ELSE块中)

非常感谢您的帮助!

您可以使用 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

最新更新