Search code examples
c#datetimerandomdate

Random date in C#


I'm looking for some succinct, modern C# code to generate a random date between Jan 1 1995 and the current date.

I'm thinking some solution that utilizes Enumerable.Range somehow may make this more succinct.


Solution

  • private Random gen = new Random();
    DateTime RandomDay()
    {
        DateTime start = new DateTime(1995, 1, 1);
        int range = (DateTime.Today - start).Days;           
        return start.AddDays(gen.Next(range));
    }
    

    For better performance if this will be called repeatedly, create the start and gen (and maybe even range) variables outside of the function.