I'm looking for some succinct C# 3 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.
I'm looking for some succinct C# 3 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.
Start with a fixed date object (Jan 1, 1995), and add a random number of days with AddDays (obviusly, pay attention not surpassing the current date).
DateTime RandomDay()
{
DateTime start = new DateTime(1995, 1, 1);
Random gen = new Random();
int range = ((TimeSpan)(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.
This is in slight response to Joel's comment about making a slighly more optimized version. Instead of returning a random date directly, why not return a generator function which can be called repeatedly to create a random date.
Func<DateTime> RandomDayFunc()
{
DateTime start = new DateTime(1995, 1, 1);
Random gen = new Random();
int range = ((TimeSpan)(DateTime.Today - start)).Days;
return () => start.AddDays(gen.Next(range));
}
Well, if you gonna present alternate optimization, we can also go for an iterator:
static IEnumerable<DateTime> RandomDay()
{
DateTime start = new DateTime(1995, 1, 1);
Random gen = new Random();
int range = ((TimeSpan)(DateTime.Today - start)).Days;
while (true)
yield return start.AddDays(gen.Next(range));
}
you could use it like this:
int i=0;
foreach(DateTime dt in RandomDay())
{
Console.WriteLine(dt);
if (++i == 10)
break;
}
// Chosen by a random dice roll. Guaranteed to be random.
return DateTime.Parse("10/07/2001");
That's the problem with random numbers, you can never be sure.