簡體   English   中英

Java:生成一個范圍之間的隨機日期(從當前日期/時間到隨機未來日期的范圍(例如,從當前日期/時間開始的5-10天)

[英]Java: Generate a random date between a range (range starting from current date/time to a random future date (e.g 5-10 days from current date/time)

Java初學者在這里。 在谷歌搜索和研究之后,這是我在生產當前日期/時間時發現的最佳方式:

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
  1. 如何將上述當前日期/時間放入變量?
  2. 如何從當前日期/時間生成RANDOM未來日期(例如,隨機范圍可以是5-10天),這意味着我沒有未來日期的固定日期。
  3. 如何將未來日期存儲到變量中?

側面注意:為什么我問問題1和問題3,這是因為我可以使用存儲兩個日期的變量進行比較和評估(用於if-else塊)

非常感謝你的幫助!

您可以使用LocalDateTime

import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
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 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 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM