Developer Tools for Random Data Generation // v2.6.1
root@generate-random:~/dates/java$ _

Generate Random Dates in Java

Complete code tutorial with examples and best practices

[ Code Example - Quick Summary ]

Language: Java

What: Generate random dates in Java using LocalDate, LocalDateTime, and JavaFaker. Covers date ranges, formatting, timezone handling, and integration with testing frameworks.

Try it: Use our interactive Dates generator or integrate this code into your Java application.

Generate random dates in Java using LocalDate, LocalDateTime, and JavaFaker. Covers date ranges, formatting, timezone handling, and integration with testing frameworks. Looking for other languages? Check our code examples in PHP , JavaScript , Python , C# , C++ , Ruby and Go or use our interactive web generator.

Java Code Example

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

public class RandomDateGenerator {
    private static final Random random = new Random();

    // Generate random date between two dates
    public static LocalDate randomDate(LocalDate startDate, LocalDate endDate) {
        long startEpochDay = startDate.toEpochDay();
        long endEpochDay = endDate.toEpochDay();
        long randomDay = ThreadLocalRandom.current().nextLong(startEpochDay, endEpochDay + 1);
        return LocalDate.ofEpochDay(randomDay);
    }

    // Generate random past date (within last N days)
    public static LocalDate randomPastDate(int daysAgo) {
        LocalDate today = LocalDate.now();
        int randomDays = random.nextInt(daysAgo + 1);
        return today.minusDays(randomDays);
    }

    // Generate random future date (within next N days)
    public static LocalDate randomFutureDate(int daysAhead) {
        LocalDate today = LocalDate.now();
        int randomDays = random.nextInt(daysAhead + 1);
        return today.plusDays(randomDays);
    }

    // Generate random birthday (18-80 years ago)
    public static LocalDate randomBirthday() {
        LocalDate today = LocalDate.now();
        int minAge = 18;
        int maxAge = 80;
        int randomAge = random.nextInt(maxAge - minAge + 1) + minAge;
        LocalDate birthYear = today.minusYears(randomAge);
        LocalDate startOfYear = LocalDate.of(birthYear.getYear(), 1, 1);
        LocalDate endOfYear = LocalDate.of(birthYear.getYear(), 12, 31);
        return randomDate(startOfYear, endOfYear);
    }

    // Generate random LocalDateTime
    public static LocalDateTime randomDateTime(LocalDate startDate, LocalDate endDate) {
        LocalDate date = randomDate(startDate, endDate);
        int hour = random.nextInt(24);
        int minute = random.nextInt(60);
        int second = random.nextInt(60);
        return LocalDateTime.of(date, java.time.LocalTime.of(hour, minute, second));
    }

    // Generate multiple random dates
    public static List<String> generateRandomDates(int count, String startDate, String endDate) {
        LocalDate start = LocalDate.parse(startDate);
        LocalDate end = LocalDate.parse(endDate);
        List<String> dates = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        for (int i = 0; i < count; i++) {
            dates.add(randomDate(start, end).format(formatter));
        }
        return dates;
    }

    // Using JavaFaker library (add dependency: com.github.javafaker:javafaker:1.0.2)
    // import com.github.javafaker.Faker;
    // Faker faker = new Faker();
    // Date randomDate = faker.date().between(startDate, endDate);
    // Date pastDate = faker.date().past(30, TimeUnit.DAYS);
    // Date futureDate = faker.date().future(90, TimeUnit.DAYS);
    // Date birthday = faker.date().birthday(18, 80);

    public static void main(String[] args) {
        LocalDate start = LocalDate.parse("2020-01-01");
        LocalDate end = LocalDate.parse("2025-12-31");

        System.out.println("Random date: " + randomDate(start, end));
        System.out.println("Past date: " + randomPastDate(30));
        System.out.println("Future date: " + randomFutureDate(90));
        System.out.println("Random birthday: " + randomBirthday());
        System.out.println("With time: " + randomDateTime(start, end));
        System.out.println("Batch: " + generateRandomDates(5, "2020-01-01", "2025-12-31"));
    }
}

[EXPLANATION]

Java 8+ introduced java.time package with LocalDate and LocalDateTime classes. toEpochDay() converts dates to days since 1970-01-01. ThreadLocalRandom provides better performance for concurrent date generation. DateTimeFormatter handles formatting with patterns like "yyyy-MM-dd" and "dd/MM/yyyy". JavaFaker offers date().between(), past(), future(), and birthday() methods for realistic test data. For timezone support, use ZonedDateTime.

Expected Output

Random date: 2023-07-15
Past date: 2024-11-17
Future date: 2025-03-15
Random birthday: 1985-04-23
With time: 2024-07-15T14:32:47
Batch: [2022-03-12, 2024-08-05, 2021-11-28, 2023-05-19, 2025-01-07]

Common Use Cases

  • Generate test data for Spring Boot applications with JPA entities
  • Create sample date ranges for JUnit and TestNG test cases
  • Populate database tables with realistic timestamp data
  • Test date-based business logic and validation rules
  • Generate time-series data for analytics and reporting

Important Notes

  • LocalDate is immutable and thread-safe
  • ThreadLocalRandom is preferred over Random for concurrent access
  • JavaFaker integrates seamlessly with JUnit, TestNG, and Spring Test
  • ChronoUnit.DAYS.between() calculates days between dates
  • For timezone-aware dates, use ZonedDateTime.now(ZoneId.of("UTC"))

Try Our Interactive Generator

Don't want to write code? Use our free web-based Dates generator with instant results.

TRY DATES GENERATOR →