What's the best practice for getting a random DateTime between two date-times?

Viewed 25351

I'm trying to randomize the value for a simple DateTime data field.

I wish to get a random date/time between two date/times (e.g. min date/time and max date/time).

So lets imagine I'm after a random date/time between

1/1/2000 10:00:00am and 1/1/2000 5:00:00pm.

Also, this code will be used in a for loop, with 100 items ... meaning all 100 items will have random date/times between the min/max date/time period.

Any ideas?

8 Answers
    DateTime RandomDateTime()
    {
        Random random = new Random();
        DateTime start = new DateTime(2010, 1, 1);
        int range = (DateTime.Today - start).Days;
        
        int randomHour = random.Next(0, 24);
        int randomMinute = random.Next(0, 60);
        int randomSecond = random.Next(0, 60);

        var randomDate = start.AddDays(random.Next(range));

        return new DateTime(randomDate.Year, randomDate.Month, randomDate.Day, randomHour, randomMinute, randomSecond);
    }
Related