WCKennedays
WCKennedays

Reputation: 309

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 beginner here. After googling and researching, this is the best way I found in my opinion to generate the current date/time:

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
  1. How do I place the above current date/time into a variable?
  2. How do I generate a RANDOM future date from current date/time (for example, the random range can be from 5 - 10 days), this means I do not have a fixed date for the future date.
  3. How do I store that future date into a variable?

SIDE NOTE: Why I asked Question 1 and 3, it's because I can use the variables storing both dates for comparison and evaluation purposes (used in if-else blocks)

Thanks a lot for your help!

Upvotes: 3

Views: 6601

Answers (1)

Sash Sinha
Sash Sinha

Reputation: 22360

You can use LocalDateTime instead:

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);
    }
}

Example Output:

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

Upvotes: 9

Related Questions