Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random DateTime between range - not unified output

I implemented the below RandomDate, but I always keep getting values closed to "From" date, i probably miss something here....

public static DateTime GetRandomDate(DateTime from, DateTime to)
    {
        var range = new TimeSpan(to.Ticks - from.Ticks);

        var rnd = new Random();

        var randTimeSpan = new TimeSpan((long)(range.TotalSeconds - rnd.Next(0, (int)range.TotalSeconds))); 

        return from + randTimeSpan;
    }
like image 913
user1025852 Avatar asked Jan 24 '13 16:01

user1025852


People also ask

How do I generate random Localdatetime?

A simple way is to convert the minimum and maximum date to their corresponding epoch day, generate a random integer between those two values and finally convert it back to a LocalDate . The epoch day is obtained with toEpochDay() which is the count of days since 1970-01-01 (ISO).


2 Answers

You could change to:

static readonly Random rnd = new Random();
public static DateTime GetRandomDate(DateTime from, DateTime to)
{
    var range = to - from;

    var randTimeSpan = new TimeSpan((long)(rnd.NextDouble() * range.Ticks)); 

    return from + randTimeSpan;
}

Explanation: I used NextDouble() because it gives a number between 0.0 and 1.0. Your return value won't be a whole number of seconds in my solution. And I moved rnd out to a field on the class/struct. Because it's best to reuse one Random instance, and not create a new one every time one needs just one additional random number.

like image 62
Jeppe Stig Nielsen Avatar answered Oct 17 '22 18:10

Jeppe Stig Nielsen


The problem is that:

var randTimeSpan = new TimeSpan((long)(range.TotalSeconds - rnd.Next(0, (int)range.TotalSeconds)));

is creating a TimeSpan from TICKS, not from SECONDS.

You need:

var randTimeSpan = TimeSpan.FromSeconds((long)(range.TotalSeconds - rnd.Next(0, (int)range.TotalSeconds)));

(Please check the cast too - it needs to be a double passed to FromSeconds)

like image 34
Matthew Watson Avatar answered Oct 17 '22 19:10

Matthew Watson