How to create a list of random dates in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class RandomDates
{
    // Generate a random date between two years using DateTime
    static DateTime RandomDate(int startYear, int endYear, Random rng) {
        // Convert start and end years to timestamps
        DateTime start = new DateTime(startYear, 1, 1);
        DateTime end   = new DateTime(endYear, 12, 31);

        // Uniform distribution over the timestamp range
        int rangeDays = (end - start).Days;
        int offset = rng.Next(0, rangeDays + 1);

        // Convert back to DateTime
        return start.AddDays(offset);
    }

    static void Main()
    {
        Random rng = new Random(); // Seed RNG
        List<DateTime> dates = new List<DateTime>();

        for (int i = 0; i < 10; i++) {
            dates.Add(RandomDate(1990, 2030, rng));
        }

        foreach (DateTime d in dates) {
            Console.WriteLine($"{d.Year}-{d.Month}-{d.Day}");
        }
    }
}



/*
run:

2015-3-4
1999-3-2
2013-9-2
1996-2-19
1992-1-21
1990-8-1
2029-5-22
1992-11-20
2001-10-23
2017-1-21

*/

 



answered 7 hours ago by avibootz
...