Tuesday, January 29, 2008

Calculating a Random Date in C#

I found myself needing to calculate a random date & time btw a given minimum and maximum date. I ended up creating the following function which appears to work very nicely.

internal DateTime CalcDate(DateTime minDate, DateTime maxDate)

//This assumes _rand is a private variable of type System.Random. It calculates a new timespan
//that can be added to the minimum date which will create a new date btw
//the min & max
TimeSpan timeSpan = maxDate - minDate;
TimeSpan randomSpan = new TimeSpan((long)(timeSpan.Ticks * _rand.NextDouble()));
return minDate+randomSpan;


One thing I ran into which I was not aware of was that while you can add DateTime & a Timespan as such: DateTime + TimeSpan, the reverse is not true, you cannot add TimeSpan+DateTime.

This to makes no sense particulary since addition is supposed to be commuatitive.

1 comment:

Perry Tribolet said...

Thanks. I added a plus-or-minus wrapper:

static DateTime GetRandomizedDateTime(DateTime trueDateTime, long milliseconds)
return CalcDate(trueDateTime.AddMilliseconds(-milliseconds), trueDateTime.AddMilliseconds(milliseconds));