Recently I needed a function that return random date. I haven't found anything that meet my needs. I've finally found the article from Tawani's blog which presents rather long function. However, I like to keep things simple, so I decided to write my own.

What are the requirements for the function:

  1. It has to be as short and simple as possible.
  2. It has to return random date from the given range [dateFrom, dateTo).
  3. The accuracy of one second is sufficient.

This is the function I've written:

DateTime RandomDate(Random rand, DateTime dateFrom, DateTime dateTo)
    DateTime randDate;

    // Get random day
    int daySpan = (int)dateTo.Subtract(dateFrom).TotalDays;
    int randDays = rand.Next(0, daySpan + 1);
    randDate = dateFrom.AddDays(randDays);

    // Get random second
    int secSpan = Math.Min(24*60*60,(int)dateTo.Subtract(randDate).TotalSeconds);
    int randSecs = rand.Next(0, secSpan + 1);
    return randDate.AddSeconds(randSecs);

The idea is simple: first it adds random day to the start date, and then adds random seconds to this. It uses `Math.Min` to protect from jumping out of the range while adding secound.