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

标签 c# datetime random difference timespan

我正在尝试生成上午 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"));
}

我做错了什么?

编辑:上面提供的代码表示我无法将 System.TimeSpan 隐式转换为 System.DateTime

最佳答案

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

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

关于c# - 如何在 C# 中生成上午 12 点到下午 6 点之间的随机时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58677437/

相关文章:

pandas - 将值插入随机行

安卓:随机异常

datetime - 如何在 Dart 中将日期/时间字符串转换为 DateTime 对象?

c# - .NET 在不同时区和不同区域设置的 SQL 中存储 DateTime

javascript - 使用 jsTimezoneDetect 脚本显示三个字母的时区代码

c# - 如何在内部网中连接到 Access 上的数据库

java - 有效地从列表中选择 N 个随机元素(无需 toArray 并更改列表)

c# - 在 C# 字典中获取相似值的最快方法

c# - 装饰通用注册的子集

c# - AutoMapper.AutoMapperMappingException异常