我正在尝试在12AM和6PM之间产生一个随机时间。到目前为止,我尝试了以下代码:
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
使用TimeSpan
之前,您必须将DateTime
转换为ToString("hh:mm tt")
TimeSpan flightTimeSpan = startWorkDay + timeSpan;
DateTime flightDateTime = new DateTime(flightTimeSpan.Ticks);
for (int i = 0; i < 10; i++)
{
Console.WriteLine(flightDateTime.ToString("hh:mm tt"));
}
这是从问题的第一行实现目标的一种方法。
我正在尝试在12AM和6PM之间产生一个随机时间。
var rnd = new Random(i);//Fixed seed, just termporarily
var minutes = rnd.Next(0, 18 * 60);
var timeOfDay = TimeSpan.FromMinutes(minutes);
for(int i = 0; i < 10; i++)
{
var rnd = new Random(i);//Fixed seed, just termporarily
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