▶ Random Everything - 100+ Free Generators // v2.8.5
root@generate-random:~/dates/code-examples$ _

Random Date Code Examples

Random calendar dates between two days in PHP, JavaScript, Python, Java, C#, C++, Ruby and Go

Each example picks a calendar date inside a range such as 2020-01-01 to 2025-12-31, a past or future date relative to today, and a birthday 18 to 80 years back, then prints them as YYYY-MM-DD. The guide explains how to draw days so that both ends of the range count, and where the calendar itself (leap years, 28- to 31-day months) breaks naive code. Prefer no code? The interactive Dates generator does the same in the browser.

Draw a day number, not a timestamp

A date range is a finite list of days: 2020-01-01 to 2025-12-31 inclusive holds 2,192 (two leap years, four common years). To pick one uniformly, convert both ends to a day count, draw an integer with both ends included, and convert back: toEpochDay() and LocalDate.ofEpochDay() in Java, toordinal() and date.fromordinal() or a timedelta(days=n) offset in Python, sys_days in C++20, Date + n in Ruby.

Drawing a Unix timestamp between two midnights and cutting off the time only works if the end bound is the last second of the end day. Taken as midnight at the start of 2025-12-31, the end date comes up only at exactly 00:00:00, about once in 189 million draws. That is why the PHP, JavaScript, C++ and Go examples push the end bound to 23:59:59.

Leap years and month lengths

The Gregorian rule: a year is a leap year if it is divisible by 4, except century years, which must be divisible by 400. So 2000 and 2024 have a February 29, while 1900 and 2100 do not. A 400-year cycle holds 97 leap days, so never hard-code 365 days per year or 30 per month; let the library count.

Building a date from random parts (year, month 1–12, day 1–31) is where this bites. Libraries treat an impossible day like February 30 in two ways:

  • They reject it: Python date() raises ValueError, Java LocalDate.of() throws DateTimeException, C# new DateTime() throws ArgumentOutOfRangeException, Ruby Date.new raises Date::Error.
  • They roll it over silently: JavaScript new Date(2023, 1, 30) and Go time.Date(2023, 2, 30, …) both become March 2, and PHP mktime() does the same.

Drawing the day from 1 to the real month length also skews the result: each February day becomes likelier than each January day.

Ages and relative dates

The PHP and JavaScript birthday functions draw between the dates exactly 80 and 18 years before today, so every result is aged 18 to 80. The Python, Java, C#, Ruby and Go versions pick a birth year, then any day in it: simpler, but someone born late in the youngest year is still 17. For age-gate tests, compute both bounds from today. Adding years to February 29 is another edge: Java, C# and Ruby clamp to February 28, while JavaScript, PHP and Go roll over to March 1.

Secure random is not needed, reproducible often is

Nobody profits from guessing the next order date in a seed file, so each language's default generator is fine. Repeatability matters more: seed it (random.seed(), new Random(42), Faker.seed(), Bogus Randomizer.Seed) so a failing test gets the same dates next run, and freeze "today", since randomPastDate(30) moves daily.

Common mistakes

  • Mixing UTC and local time. A date drawn in UTC and printed with local-time functions shifts by a day west of Greenwich. Use one zone, or date-only types (LocalDate, DateOnly, date, Date) that carry no zone.
  • Daylight saving days. Between local midnights, one day per year has 23 hours and one has 25, so drawing seconds makes those days slightly less or more likely, and adding 86,400 seconds can land on the same calendar date.
  • Parsing ambiguous input. 03/04/2025 is March 4 in the US, April 3 in Europe. Use ISO 8601 YYYY-MM-DD, which also sorts as text.
  • Uniform when real data is not. Real orders cluster on weekdays and before holidays; uniform dates suit unit tests, not analytics tests.

Common Use Cases

  • Seed data with signup, order and invoice dates for Laravel, Django, Rails, Spring or EF Core models
  • Birth dates for age calculation, age-gate and validation tests
  • Events for calendar, booking and date-picker components
  • Date columns for filtering, sorting and date-range query tests
  • Daily time-series rows for charts, reports and analytics pipelines

Random Date Code Examples in PHP

Generate random dates in PHP using DateTime and Carbon. Covers date ranges, formatting, timezones, Unix timestamps, and past/future date generation for testing.

<?php
// Generate random date between two dates
function randomDate($startDate, $endDate) {
    $startTimestamp = strtotime($startDate);
    $endTimestamp = strtotime("$endDate 23:59:59"); // include the whole end day
    $randomTimestamp = mt_rand($startTimestamp, $endTimestamp);
    return date("Y-m-d", $randomTimestamp);
}

// Generate random DateTime object
function randomDateTime($startDate, $endDate) {
    $startTimestamp = strtotime($startDate);
    $endTimestamp = strtotime($endDate);
    $randomTimestamp = mt_rand($startTimestamp, $endTimestamp);
    return new DateTime("@$randomTimestamp");
}

// Generate random past date (within last N days)
function randomPastDate($daysAgo = 365) {
    $timestamp = time() - mt_rand(0, $daysAgo * 86400);
    return date("Y-m-d", $timestamp);
}

// Generate random future date (within next N days)
function randomFutureDate($daysAhead = 365) {
    $timestamp = time() + mt_rand(0, $daysAhead * 86400);
    return date("Y-m-d", $timestamp);
}

// Generate random date with specific format
function randomDateFormatted($format = "Y-m-d H:i:s") {
    $start = strtotime("2020-01-01");
    $end = strtotime("2025-12-31");
    $random = mt_rand($start, $end);
    return date($format, $random);
}

// Generate random birthday (18-80 years ago)
function randomBirthday() {
    $minAge = 18;
    $maxAge = 80;
    $minDate = strtotime("-$maxAge years");
    $maxDate = strtotime("-$minAge years");
    $random = mt_rand($minDate, $maxDate);
    return date("Y-m-d", $random);
}

// Generate multiple random dates
function generateRandomDates($count = 10, $startDate = "2020-01-01", $endDate = "2025-12-31") {
    $dates = [];
    for ($i = 0; $i < $count; $i++) {
        $dates[] = randomDate($startDate, $endDate);
    }
    return $dates;
}

// Using Carbon library (install: composer require nesbot/carbon)
// use Carbon\Carbon;
// $randomDate = Carbon::createFromTimestamp(mt_rand(
//     Carbon::parse("2020-01-01")->timestamp,
//     Carbon::parse("2025-12-31")->timestamp
// ));
// $pastDate = Carbon::now()->subDays(mt_rand(1, 365));
// $futureDate = Carbon::now()->addDays(mt_rand(1, 365));

// Usage examples
echo "Random date: " . randomDate("2020-01-01", "2025-12-31") . "\n";
echo "Past date: " . randomPastDate(30) . "\n";
echo "Future date: " . randomFutureDate(90) . "\n";
echo "Random birthday: " . randomBirthday() . "\n";
echo "Formatted: " . randomDateFormatted("d/m/Y") . "\n";
print_r(generateRandomDates(5));

How it works in PHP

This implementation uses strtotime() to convert date strings to Unix timestamps, then mt_rand() to generate random timestamps between the range, and date() to format the result. The DateTime class provides object-oriented date handling. For production use, Carbon library offers intuitive methods like subDays(), addDays(), and timezone support. Common formats: Y-m-d (2024-12-17), d/m/Y (17/12/2024), Y-m-d H:i:s (2024-12-17 14:30:00).

Sample output

Random date: 2023-07-15
Past date: 2024-11-17
Future date: 2025-03-15
Random birthday: 1985-04-23
Formatted: 15/07/2023
Array
(
    [0] => 2022-03-12
    [1] => 2024-08-05
    [2] => 2021-11-28
    [3] => 2023-05-19
    [4] => 2025-01-07
)

PHP notes

  • date() and strtotime() use the date.timezone setting; call date_default_timezone_set('UTC') or use DateTimeImmutable with an explicit zone.
  • (new DateTimeImmutable('2025-01-31'))->modify('+1 month') gives 2025-03-03, not February 28; use 'last day of next month' when you mean the month end.
  • checkdate($month, $day, $year) validates parts, and date('t', $ts) returns the number of days in that month.

Random Date Code Examples in JavaScript

Generate random dates in JavaScript for frontend and Node.js applications. Covers Date objects, date ranges, formatting with moment.js and date-fns, and timezone handling.

// Generate random date between two dates
function randomDate(startDate, endDate) {
    const start = new Date(startDate).getTime();
    const end = new Date(endDate).getTime() + 86400000 - 1; // include the whole end day
    const randomTimestamp = Math.floor(Math.random() * (end - start + 1)) + start;
    return new Date(randomTimestamp);
}

// Generate random date as ISO string
function randomDateISO(startDate, endDate) {
    return randomDate(startDate, endDate).toISOString().split("T")[0];
}

// Generate random past date (within last N days)
function randomPastDate(daysAgo = 365) {
    const now = new Date();
    const past = new Date(now.getTime() - Math.random() * daysAgo * 86400000);
    return past;
}

// Generate random future date (within next N days)
function randomFutureDate(daysAhead = 365) {
    const now = new Date();
    const future = new Date(now.getTime() + Math.random() * daysAhead * 86400000);
    return future;
}

// Generate random birthday (18-80 years ago)
function randomBirthday() {
    const now = new Date();
    const minAge = 18;
    const maxAge = 80;
    const minDate = new Date(now.getFullYear() - maxAge, now.getMonth(), now.getDate());
    const maxDate = new Date(now.getFullYear() - minAge, now.getMonth(), now.getDate());
    return randomDate(minDate, maxDate);
}

// Format date as YYYY-MM-DD
function formatDate(date) {
    const year = date.getUTCFullYear();
    const month = String(date.getUTCMonth() + 1).padStart(2, "0");
    const day = String(date.getUTCDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
}

// Generate multiple random dates
function generateRandomDates(count = 10, startDate = "2020-01-01", endDate = "2025-12-31") {
    return Array.from({length: count}, () =>
        formatDate(randomDate(startDate, endDate))
    );
}

// Using moment.js (npm install moment)
// const moment = require("moment");
// const randomMoment = moment(Math.random() * (
//     moment("2025-12-31").valueOf() - moment("2020-01-01").valueOf()
// ) + moment("2020-01-01").valueOf());

// Using date-fns (npm install date-fns)
// const { addDays, subDays } = require("date-fns");
// const pastDate = subDays(new Date(), Math.floor(Math.random() * 365));
// const futureDate = addDays(new Date(), Math.floor(Math.random() * 365));

// Usage examples
console.log("Random date:", formatDate(randomDate("2020-01-01", "2025-12-31")));
console.log("Past date:", formatDate(randomPastDate(30)));
console.log("Future date:", formatDate(randomFutureDate(90)));
console.log("Random birthday:", formatDate(randomBirthday()));
console.log("ISO format:", randomDateISO("2020-01-01", "2025-12-31"));
console.log("Batch:", generateRandomDates(5));

How it works in JavaScript

JavaScript's Date object uses milliseconds since Unix epoch. getTime() returns milliseconds, and Math.random() generates values between the range. The toISOString() method outputs ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ). Month indexes are 0-based (0=January, 11=December). Libraries like moment.js and date-fns provide timezone support, localization, and convenient manipulation methods. 86400000 milliseconds = 1 day.

Sample output

Random date: 2023-07-15
Past date: 2024-11-17
Future date: 2025-03-15
Random birthday: 1985-04-23
ISO format: 2023-07-15
Batch: [ "2022-03-12", "2024-08-05", "2021-11-28", "2023-05-19", "2025-01-07" ]

JavaScript notes

  • A date-only string such as "2020-01-01" is parsed as UTC midnight, but "2020-01-01T00:00" is parsed as local time; that is why formatDate() reads the UTC fields.
  • Months are 0-based in new Date(y, m, d) and the constructor rolls over invalid days: new Date(2023, 1, 29) is March 1.
  • toISOString().split("T")[0] is always the UTC date, which may differ from the local calendar date.

Random Date Code Examples in Python

Generate random dates in Python using datetime and Faker library. Covers date ranges, timedelta, formatting, timezone handling, and realistic test data generation.

import random
from datetime import datetime, timedelta

# Generate random date between two dates
def random_date(start_date, end_date):
    start = datetime.strptime(start_date, "%Y-%m-%d")
    end = datetime.strptime(end_date, "%Y-%m-%d")
    delta = end - start
    random_days = random.randint(0, delta.days)
    return start + timedelta(days=random_days)

# Generate random past date (within last N days)
def random_past_date(days_ago=365):
    today = datetime.now()
    past = today - timedelta(days=random.randint(0, days_ago))
    return past

# Generate random future date (within next N days)
def random_future_date(days_ahead=365):
    today = datetime.now()
    future = today + timedelta(days=random.randint(0, days_ahead))
    return future

# Generate random birthday (18-80 years ago)
def random_birthday():
    today = datetime.now()
    min_age = 18
    max_age = 80
    years_ago = random.randint(min_age, max_age)
    birth_year = today.year - years_ago
    return random_date(f"{birth_year}-01-01", f"{birth_year}-12-31")

# Generate random datetime with time component
def random_datetime(start_date, end_date):
    date = random_date(start_date, end_date)
    random_hour = random.randint(0, 23)
    random_minute = random.randint(0, 59)
    random_second = random.randint(0, 59)
    return datetime(date.year, date.month, date.day,
                   random_hour, random_minute, random_second)

# Generate multiple random dates
def generate_random_dates(count=10, start_date="2020-01-01", end_date="2025-12-31"):
    return [random_date(start_date, end_date).strftime("%Y-%m-%d")
            for _ in range(count)]

# Using Faker library (install: pip install faker)
# from faker import Faker
# fake = Faker()
# random_date = fake.date_between(start_date="-1y", end_date="today")
# past_date = fake.past_date(start_date="-30d")
# future_date = fake.future_date(end_date="+90d")
# birthday = fake.date_of_birth(minimum_age=18, maximum_age=80)
# datetime_obj = fake.date_time_between(start_date="-1y", end_date="now")

# Usage examples
print("Random date:", random_date("2020-01-01", "2025-12-31").strftime("%Y-%m-%d"))
print("Past date:", random_past_date(30).strftime("%Y-%m-%d"))
print("Future date:", random_future_date(90).strftime("%Y-%m-%d"))
print("Random birthday:", random_birthday().strftime("%Y-%m-%d"))
print("With time:", random_datetime("2024-01-01", "2024-12-31").strftime("%Y-%m-%d %H:%M:%S"))
print("Batch:", generate_random_dates(5))

How it works in Python

Python's datetime module provides date/time handling. strptime() parses strings to datetime objects, strftime() formats them. timedelta represents time differences for date arithmetic. The Faker library offers date_between(), past_date(), future_date(), and date_of_birth() with intuitive parameters. Format codes: %Y (year), %m (month), %d (day), %H (hour), %M (minute), %S (second). For timezone support, use pytz or built-in timezone.

Sample 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-15 14:32:47
Batch: ["2022-03-12", "2024-08-05", "2021-11-28", "2023-05-19", "2025-01-07"]

Python notes

  • random.randint(0, delta.days) includes both ends, so the end date is reachable.
  • calendar.isleap(y) and calendar.monthrange(y, m)[1] give leap years and month lengths; date(2023, 2, 29) raises ValueError.
  • Use date rather than datetime for pure calendar dates; datetime.utcnow() is deprecated since Python 3.12 in favor of datetime.now(timezone.utc).

Random Date Code Examples in Java

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

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

How it works in Java

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.

Sample 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]

Java notes

  • ThreadLocalRandom.nextLong(origin, bound) excludes bound, hence endEpochDay + 1.
  • plusMonths(1) clamps 2025-01-31 to 2025-02-28; Year.isLeap(y) and YearMonth.of(y, m).lengthOfMonth() answer calendar questions.
  • JavaFaker has had no release since 1.0.2 (2020); Datafaker (net.datafaker) is its maintained fork with the same date() methods.

Random Date Code Examples in C#

Generate random dates in C# using DateTime and Bogus library. Covers date ranges, formatting, timezone handling with DateTimeOffset, and integration with xUnit/NUnit.

using System;
using System.Linq;

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

    // Generate random date between two dates
    public static DateTime RandomDate(DateTime startDate, DateTime endDate)
    {
        int range = (endDate - startDate).Days;
        return startDate.AddDays(random.Next(range + 1));
    }

    // Generate random past date (within last N days)
    public static DateTime RandomPastDate(int daysAgo = 365)
    {
        return DateTime.Now.AddDays(-random.Next(daysAgo + 1));
    }

    // Generate random future date (within next N days)
    public static DateTime RandomFutureDate(int daysAhead = 365)
    {
        return DateTime.Now.AddDays(random.Next(daysAhead + 1));
    }

    // Generate random birthday (18-80 years ago)
    public static DateTime RandomBirthday()
    {
        var today = DateTime.Now;
        var minAge = 18;
        var maxAge = 80;
        var randomAge = random.Next(minAge, maxAge + 1);
        var birthYear = today.Year - randomAge;
        var startOfYear = new DateTime(birthYear, 1, 1);
        var endOfYear = new DateTime(birthYear, 12, 31);
        return RandomDate(startOfYear, endOfYear);
    }

    // Generate random DateTime with time component
    public static DateTime RandomDateTime(DateTime startDate, DateTime endDate)
    {
        var date = RandomDate(startDate, endDate);
        var hour = random.Next(24);
        var minute = random.Next(60);
        var second = random.Next(60);
        return new DateTime(date.Year, date.Month, date.Day, hour, minute, second);
    }

    // Generate random DateTimeOffset (timezone-aware)
    public static DateTimeOffset RandomDateTimeOffset(DateTime startDate, DateTime endDate)
    {
        var dateTime = RandomDateTime(startDate, endDate);
        return new DateTimeOffset(dateTime, TimeSpan.Zero);
    }

    // Generate multiple random dates
    public static string[] GenerateRandomDates(int count, string startDate, string endDate)
    {
        var start = DateTime.Parse(startDate);
        var end = DateTime.Parse(endDate);

        return Enumerable.Range(0, count)
            .Select(_ => RandomDate(start, end).ToString("yyyy-MM-dd"))
            .ToArray();
    }

    // Using Bogus library (Install-Package Bogus)
    // using Bogus;
    // var faker = new Faker();
    // DateTime randomDate = faker.Date.Between(startDate, endDate);
    // DateTime pastDate = faker.Date.Past(1); // 1 year ago
    // DateTime futureDate = faker.Date.Future(1); // 1 year ahead
    // DateTime birthday = faker.Date.Past(80, DateTime.Now.AddYears(-18));
    // DateTimeOffset recentDate = faker.Date.RecentOffset(30); // Last 30 days

    public static void Main()
    {
        var start = new DateTime(2020, 1, 1);
        var end = new DateTime(2025, 12, 31);

        Console.WriteLine($"Random date: {RandomDate(start, end):yyyy-MM-dd}");
        Console.WriteLine($"Past date: {RandomPastDate(30):yyyy-MM-dd}");
        Console.WriteLine($"Future date: {RandomFutureDate(90):yyyy-MM-dd}");
        Console.WriteLine($"Random birthday: {RandomBirthday():yyyy-MM-dd}");
        Console.WriteLine($"With time: {RandomDateTime(start, end):yyyy-MM-dd HH:mm:ss}");
        Console.WriteLine($"Batch: {string.Join(", ", GenerateRandomDates(5, "2020-01-01", "2025-12-31"))}");
    }
}

How it works in C#

C#'s DateTime struct represents dates and times. TimeSpan represents time intervals for date arithmetic. AddDays(), AddMonths(), AddYears() perform date calculations. DateTimeOffset includes timezone information. String interpolation with format specifiers like {date:yyyy-MM-dd} simplifies formatting. Bogus library provides Date.Between(), Past(), Future(), and Recent() methods for realistic test data generation in xUnit, NUnit, and MSTest.

Sample 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-15 14:32:47
Batch: 2022-03-12, 2024-08-05, 2021-11-28, 2023-05-19, 2025-01-07

C# notes

  • random.Next(range + 1) includes the end date because Next(n) excludes n.
  • On .NET 6+, DateOnly stores a date with no time or zone, and DateOnly.FromDayNumber() maps a drawn day number back to a date; Random.Shared is the thread-safe generator.
  • DateTime.IsLeapYear(y) and DateTime.DaysInMonth(y, m) cover the calendar rules; DateTime.Parse follows the current culture, so prefer ParseExact with "yyyy-MM-dd".

Random Date Code Examples in C++

Generate random dates in C++ using chrono library and time_t. Covers date ranges, formatting, C++20 calendar features, and random date generation for testing.

#include <iostream>
#include <random>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>

class RandomDateGenerator {
private:
    std::mt19937 rng;

public:
    RandomDateGenerator() : rng(std::random_device{}()) {}

    // Convert date string to time_point
    std::chrono::system_clock::time_point parseDate(const std::string& dateStr) {
        std::tm tm = {};
        tm.tm_isdst = -1; // let mktime decide whether DST applies
        std::istringstream ss(dateStr);
        ss >> std::get_time(&tm, "%Y-%m-%d");
        return std::chrono::system_clock::from_time_t(std::mktime(&tm));
    }

    // Generate random date between two dates
    std::chrono::system_clock::time_point randomDate(
        const std::string& startDate,
        const std::string& endDate) {

        auto start = parseDate(startDate);
        auto end = parseDate(endDate) + std::chrono::hours(24) - std::chrono::seconds(1); // whole end day

        auto startTime = std::chrono::system_clock::to_time_t(start);
        auto endTime = std::chrono::system_clock::to_time_t(end);

        std::uniform_int_distribution<std::time_t> dist(startTime, endTime);
        std::time_t randomTime = dist(rng);

        return std::chrono::system_clock::from_time_t(randomTime);
    }

    // Generate random past date (within last N days)
    std::chrono::system_clock::time_point randomPastDate(int daysAgo = 365) {
        auto now = std::chrono::system_clock::now();
        auto maxOffset = std::chrono::hours(24 * daysAgo);

        std::uniform_int_distribution<long long> dist(0, maxOffset.count());
        auto randomOffset = std::chrono::hours(dist(rng));

        return now - randomOffset;
    }

    // Generate random future date (within next N days)
    std::chrono::system_clock::time_point randomFutureDate(int daysAhead = 365) {
        auto now = std::chrono::system_clock::now();
        auto maxOffset = std::chrono::hours(24 * daysAhead);

        std::uniform_int_distribution<long long> dist(0, maxOffset.count());
        auto randomOffset = std::chrono::hours(dist(rng));

        return now + randomOffset;
    }

    // Format time_point as string
    std::string formatDate(const std::chrono::system_clock::time_point& tp) {
        std::time_t time = std::chrono::system_clock::to_time_t(tp);
        std::tm* tm = std::localtime(&time);
        std::ostringstream oss;
        oss << std::put_time(tm, "%Y-%m-%d");
        return oss.str();
    }

    // Format with time component
    std::string formatDateTime(const std::chrono::system_clock::time_point& tp) {
        std::time_t time = std::chrono::system_clock::to_time_t(tp);
        std::tm* tm = std::localtime(&time);
        std::ostringstream oss;
        oss << std::put_time(tm, "%Y-%m-%d %H:%M:%S");
        return oss.str();
    }
};

int main() {
    RandomDateGenerator generator;

    auto randomDate = generator.randomDate("2020-01-01", "2025-12-31");
    auto pastDate = generator.randomPastDate(30);
    auto futureDate = generator.randomFutureDate(90);

    std::cout << "Random date: " << generator.formatDate(randomDate) << std::endl;
    std::cout << "Past date: " << generator.formatDate(pastDate) << std::endl;
    std::cout << "Future date: " << generator.formatDate(futureDate) << std::endl;
    std::cout << "With time: " << generator.formatDateTime(randomDate) << std::endl;

    return 0;
}

How it works in C++

C++11 introduced std::chrono for time operations. system_clock::time_point represents points in time. time_t is Unix timestamp (seconds since 1970). std::get_time() and std::put_time() handle parsing and formatting with strftime patterns. std::uniform_int_distribution generates random timestamps. C++20 adds std::chrono::year_month_day for calendar arithmetic. std::mt19937 provides high-quality randomness.

Sample output

Random date: 2023-07-15
Past date: 2024-11-17
Future date: 2025-03-15
With time: 2024-07-15 14:32:47

C++ notes

  • C++20 std::chrono::year_month_day and sys_days let you draw a day count and convert back with no time_t or time zone; ymd.ok() rejects February 30.
  • std::mktime interprets std::tm as local time; tm_isdst = -1 lets it work out daylight saving for summer dates.
  • std::localtime returns a pointer to shared static storage; use localtime_r (POSIX) or localtime_s (Windows) in threaded code.

Random Date Code Examples in Ruby

Generate random dates in Ruby using Date, Time, and DateTime classes with Faker gem. Covers date ranges, formatting, timezone handling, and Rails/RSpec integration.

require "date"
require "time"

# Generate random date between two dates
def random_date(start_date, end_date)
  start = Date.parse(start_date)
  finish = Date.parse(end_date)
  start + rand(0..(finish - start).to_i)
end

# Generate random past date (within last N days)
def random_past_date(days_ago = 365)
  Date.today - rand(0..days_ago)
end

# Generate random future date (within next N days)
def random_future_date(days_ahead = 365)
  Date.today + rand(0..days_ahead)
end

# Generate random birthday (18-80 years ago)
def random_birthday
  today = Date.today
  min_age = 18
  max_age = 80
  years_ago = rand(min_age..max_age)
  birth_year = today.year - years_ago
  random_date("#{birth_year}-01-01", "#{birth_year}-12-31")
end

# Generate random Time object
def random_time(start_date, end_date)
  start_time = Time.parse(start_date).to_i
  end_time = Time.parse(end_date).to_i
  random_timestamp = rand(start_time..end_time)
  Time.at(random_timestamp)
end

# Generate random DateTime
def random_datetime(start_date, end_date)
  date = random_date(start_date, end_date)
  hour = rand(0..23)
  minute = rand(0..59)
  second = rand(0..59)
  DateTime.new(date.year, date.month, date.day, hour, minute, second)
end

# Generate multiple random dates
def generate_random_dates(count = 10, start_date = "2020-01-01", end_date = "2025-12-31")
  count.times.map { random_date(start_date, end_date).strftime("%Y-%m-%d") }
end

# Using Faker gem (add to Gemfile: gem 'faker')
# require 'faker'
# random_date = Faker::Date.between(from: "2020-01-01", to: "2025-12-31")
# past_date = Faker::Date.backward(days: 30)
# future_date = Faker::Date.forward(days: 90)
# birthday = Faker::Date.birthday(min_age: 18, max_age: 80)
# random_time = Faker::Time.between(from: 1.year.ago, to: Date.today)

# Usage examples
puts "Random date: #{random_date('2020-01-01', '2025-12-31')}"
puts "Past date: #{random_past_date(30)}"
puts "Future date: #{random_future_date(90)}"
puts "Random birthday: #{random_birthday}"
puts "With time: #{random_time('2024-01-01', '2024-12-31').strftime('%Y-%m-%d %H:%M:%S')}"
puts "Batch: #{generate_random_dates(5).join(', ')}"

How it works in Ruby

Ruby provides Date, Time, and DateTime classes. Date.parse() converts strings to Date objects. to_time.to_i converts to Unix timestamp. rand(start..end) generates random integers in a range. strftime() formats dates with patterns like "%Y-%m-%d". Faker gem offers Date.between(), backward(), forward(), and birthday() methods. Rails adds ActiveSupport methods like 1.year.ago and 30.days.from_now.

Sample 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-15 14:32:47
Batch: 2022-03-12, 2024-08-05, 2021-11-28, 2023-05-19, 2025-01-07

Ruby notes

  • Date + n adds days, and Date#>> adds months with clamping: Date.new(2024, 1, 31) >> 1 is 2024-02-29.
  • Date.leap?(y) and Date.valid_date?(y, m, d) check the calendar without raising.
  • rand(range) works with a Date range too: rand(Date.new(2020, 1, 1)..Date.new(2025, 12, 31)).

Random Date Code Examples in Go

Generate random dates in Go using time package. Covers time.Time, date ranges, formatting, timezone handling, and random date generation for microservices testing.

package main

import (
    "fmt"
    "math/rand"
    "time"
)

// Generate random date between two dates
func randomDate(startDate, endDate string) time.Time {
    layout := "2006-01-02"
    start, _ := time.Parse(layout, startDate)
    end, _ := time.Parse(layout, endDate)

    delta := end.Unix() - start.Unix() + 86399 // through 23:59:59 of the end date
    randomSeconds := rand.Int63n(delta + 1)

    return start.Add(time.Duration(randomSeconds) * time.Second)
}

// Generate random past date (within last N days)
func randomPastDate(daysAgo int) time.Time {
    now := time.Now()
    maxSeconds := int64(daysAgo * 86400)
    randomSeconds := rand.Int63n(maxSeconds + 1)
    return now.Add(-time.Duration(randomSeconds) * time.Second)
}

// Generate random future date (within next N days)
func randomFutureDate(daysAhead int) time.Time {
    now := time.Now()
    maxSeconds := int64(daysAhead * 86400)
    randomSeconds := rand.Int63n(maxSeconds + 1)
    return now.Add(time.Duration(randomSeconds) * time.Second)
}

// Generate random birthday (18-80 years ago)
func randomBirthday() time.Time {
    now := time.Now()
    minAge := 18
    maxAge := 80
    yearsAgo := rand.Intn(maxAge-minAge+1) + minAge
    birthYear := now.Year() - yearsAgo

    startDate := fmt.Sprintf("%d-01-01", birthYear)
    endDate := fmt.Sprintf("%d-12-31", birthYear)

    return randomDate(startDate, endDate)
}

// Generate random time with specific components
func randomDateTime(startDate, endDate string) time.Time {
    date := randomDate(startDate, endDate)
    hour := rand.Intn(24)
    minute := rand.Intn(60)
    second := rand.Intn(60)

    return time.Date(
        date.Year(), date.Month(), date.Day(),
        hour, minute, second, 0, time.UTC,
    )
}

// Generate multiple random dates
func generateRandomDates(count int, startDate, endDate string) []string {
    dates := make([]string, count)
    layout := "2006-01-02"

    for i := 0; i < count; i++ {
        dates[i] = randomDate(startDate, endDate).Format(layout)
    }

    return dates
}

func main() {
    layout := "2006-01-02"
    layoutWithTime := "2006-01-02 15:04:05"

    fmt.Println("Random date:", randomDate("2020-01-01", "2025-12-31").Format(layout))
    fmt.Println("Past date:", randomPastDate(30).Format(layout))
    fmt.Println("Future date:", randomFutureDate(90).Format(layout))
    fmt.Println("Random birthday:", randomBirthday().Format(layout))
    fmt.Println("With time:", randomDateTime("2024-01-01", "2024-12-31").Format(layoutWithTime))
    fmt.Println("Batch:", generateRandomDates(5, "2020-01-01", "2025-12-31"))
}

How it works in Go

Go's time package uses time.Time for date/time representation. time.Parse() parses strings using layout "2006-01-02" (Go's reference time). Unix() returns seconds since 1970-01-01. Add() and Sub() perform date arithmetic with time.Duration. Format() converts to strings using the same reference layout. Go's timezone support uses time.LoadLocation(). Since Go 1.20 the global math/rand source is seeded automatically, so no rand.Seed() call is needed.

Sample 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-15 14:32:47
Batch: [2022-03-12 2024-08-05 2021-11-28 2023-05-19 2025-01-07]

Go notes

  • time.Parse with layout "2006-01-02" returns UTC, and the code stays in UTC, so no daylight saving shift applies.
  • time.Date normalizes out-of-range values: day 0 of the next month is the last day of this one, so time.Date(y, m+1, 0, 0, 0, 0, 0, time.UTC).Day() is the month length.
  • t.AddDate(0, 1, 0) on January 31 gives March 3 (March 2 in leap years), not the end of February.

Try the Interactive Generator

Need values right now rather than code? The Dates generator runs in the browser and exports to TXT, CSV or JSON.

OPEN THE DATES GENERATOR →