#include <iostream>
#include <vector>
#include <random>
#include <chrono>
// Generate a single random valid calendar date using C++20 chrono types
std::chrono::year_month_day random_date(std::mt19937 &rng) {
// Random year between 1990 and 2030 (inclusive)
std::uniform_int_distribution<int> yearDist(1990, 2030);
// Random month between 1 and 12
std::uniform_int_distribution<unsigned> monthDist(1, 12);
int year = yearDist(rng);
unsigned month = monthDist(rng);
// Number of days in each month (February handled separately)
static const unsigned days_in_month[] =
{31,28,31,30,31,30,31,31,30,31,30,31};
// Start with the normal number of days for this month
unsigned dayMax = days_in_month[month - 1];
// If February, check whether this year is a leap year
if (month == 2) {
bool leap = std::chrono::year{year}.is_leap();
if (leap) dayMax = 29; // February has 29 days in leap years
}
// Random day between 1 and the correct number of days for this month
std::uniform_int_distribution<unsigned> dayDist(1, dayMax);
unsigned day = dayDist(rng);
// Construct a strongly‑typed chrono date object
return std::chrono::year_month_day{
std::chrono::year{year},
std::chrono::month{month},
std::chrono::day{day}
};
}
int main() {
// Initialize a high‑quality random number generator
std::mt19937 rng(std::random_device{}());
// Store the generated dates
std::vector<std::chrono::year_month_day> dates;
// Generate 10 random dates
for (int i = 0; i < 10; i++) {
dates.push_back(random_date(rng));
}
// Print each date in YYYY-MM-DD format
for (auto d : dates) {
std::cout << int(d.year()) << "-"
<< unsigned(d.month()) << "-"
<< unsigned(d.day()) << "\n";
}
}
/*
run:
1996-2-16
2028-6-4
2000-2-1
1996-7-10
1993-9-9
2027-2-4
2005-7-31
1994-2-8
2005-6-2
2016-6-24
*/