Search code examples
c#datetimerandomdifferencetimespan

How do I generate a random time between 12AM and 6PM in C#?


I am trying to generate a random time between 12AM and 6PM. So far I tried the following code:

Random random = new Random();

TimeSpan startWorkDay = new TimeSpan(5, 0, 0);
TimeSpan endWorkDay = new TimeSpan(12, 0, 0);

TimeSpan numberOfMinutes = endWorkDay - startWorkDay;
TimeSpan timeSpan = new TimeSpan(0, random.Next(0, (int)numberOfMinutes.TotalMinutes), 0);

DateTime flightTimeSpan = startWorkDay + timeSpan;

for (int i = 0; i < 10; i++)
{
    Console.WriteLine(flightTimeSpan.ToString("hh:mm tt"));
}

what am I doing wrong?

EDIT: The code provided above is saying that I cannot implicitly convert System.TimeSpan to System.DateTime


Solution

  • Here is a way to achieve the goal from the first line of the question.

    I am trying to generate a random time between 12AM and 6PM.

    var rnd = new Random(i);//Fixed seed, just termporarily
    var minutes = rnd.Next(0, 18 * 60);
    var timeOfDay = TimeSpan.FromMinutes(minutes);
    
    

    Test

    var rnd = new Random(i);//Fixed seed, just as an example
    for(int i = 0; i < 10; i++)
    {
        var minutes = rnd.Next(0, 18 * 60);
    
        var timeOfDay = TimeSpan.FromMinutes(minutes);
    
        var dt = new DateTime(2019, 11, 03) + timeOfDay;
    
        Console.WriteLine(dt.ToString("hh:mm tt"));
    }
    
    // .NETCoreApp,Version=v3.0
    01:04 PM
    04:28 AM
    01:52 PM
    05:17 AM
    02:41 PM
    06:05 AM
    03:29 PM
    06:53 AM
    04:18 PM
    07:42 AM