Blog

How To: Random DateTime(s)

I had a small database project that needed about a million records to stress test its performance and the front office application. For some reason, working with DateTime in C# is not always straightforward, and you might need some research and trial & errors until you can get something as simple as random date/time generation working. I’ve implemented a nice and simple method to help anyone and specially remember me if I ever need it again:

public DateTime GetRandomDate(DateTime from, DateTime to)
{
    TimeSpan range = new TimeSpan(to.Ticks - from.Ticks);
    return from + new TimeSpan((long) (range.Ticks * rnd.NextDouble()));
}

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

7 Responses to “How To: Random DateTime(s)”

  1. Hi.
    So you can use DateTime.FromBinary(/* Your Random Number As Int64 */).
    For
    more information: http://msdn2.microsoft.com/en-us/library/system.datetime.frombinary.aspx

  2. alexmipego says:

    You’re correct, but that
    doesn’t give you a random date between 2 other dates, you would need to serialize both the “from” and “to” dates and then randomize between those values. I believe this is quite
    simpler.

  3. Oops. You right. i didn’t pay attention to “From” and “To”. 😉

  4. […] the code to run. Generating random dates is, in my experience, the least obvious piece, check this previous post for some tips. The time it takes to generate the data and record it using your real world logging […]

  5. AllenSu says:

    Hi.
    this solution is important with me.
    thanks.

  6. fennoo says:

    what is “rnd” ???

  7. alexmipego says:

    @fennoo
    Its the random function.

Leave a Reply

For spam filtering purposes, please copy the number 7640 to the field below: