如何在 C# 中生成中午 12 点到下午 6 点之间的随机时间?

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

我正在尝试生成中午 12 点到下午 6 点之间的随机时间。到目前为止,我尝试了以下代码:

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"));
}

我做错了什么?

编辑: 上面提供的代码是说我 cannot implicitly convert System.TimeSpan to System.DateTime

在使用 ToString("hh:mm tt")

之前,您必须将 TimeSpan 转换为 DateTime
TimeSpan flightTimeSpan = startWorkDay + timeSpan;
DateTime flightDateTime = new DateTime(flightTimeSpan.Ticks);

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

这是从问题的第一行开始实现目标的方法。

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);

测试

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