Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/275.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 什么';在两个约会时间之间获得一个随机日期时间的最佳实践是什么?_C#_.net_Datetime_Random - Fatal编程技术网

C# 什么';在两个约会时间之间获得一个随机日期时间的最佳实践是什么?

C# 什么';在两个约会时间之间获得一个随机日期时间的最佳实践是什么?,c#,.net,datetime,random,C#,.net,Datetime,Random,我正在尝试将一个简单的DateTime数据字段的值随机化 我希望获得两个日期/时间之间的随机日期/时间(例如,最小日期/时间和最大日期/时间) 所以,让我们想象一下,我正在寻找一个随机的日期/时间 2000年1月1日上午10:00:00和2000年1月1日下午5:00:00 此外,此代码将在for循环中使用,包含100项。。。这意味着所有100个项目将在最小/最大日期/时间段之间具有随机日期/时间 有什么想法吗?您可以尝试使用: var randomTest = new Random(); T

我正在尝试将一个简单的
DateTime
数据字段的值随机化

我希望获得两个日期/时间之间的随机日期/时间(例如,最小日期/时间和最大日期/时间)

所以,让我们想象一下,我正在寻找一个随机的日期/时间

2000年1月1日上午10:00:00
2000年1月1日下午5:00:00

此外,此代码将在for循环中使用,包含100项。。。这意味着所有100个项目将在最小/最大日期/时间段之间具有随机日期/时间

有什么想法吗?

您可以尝试使用:

var randomTest = new Random();

TimeSpan timeSpan = endDate - startDate;
TimeSpan newSpan = new TimeSpan(0, randomTest.Next(0, (int)timeSpan.TotalMinutes), 0);
DateTime newDate = startDate + newSpan;
这将给你不同的时间到一分钟。如果您想要100(或任何大于1的事物)
DateTime
s,那么只需创建一次
Random
对象。详细解释了为什么快速连续创建多个
随机
对象是个坏主意

使用不同的
TimeSpan
构造函数将为您提供不同的粒度。从:

TimeSpan(Int64)将新的TimeSpan初始化为指定的刻度数。
时间跨度(Int32、Int32、Int32)将新时间跨度初始化为指定的小时、分钟和秒数。
时间跨度(Int32、Int32、Int32、Int32)将新时间跨度初始化为指定的时间跨度数 天、小时、分钟和秒。
时间跨度(Int32、Int32、Int32、Int32、Int32)将新时间跨度初始化为指定的天数、小时数、分钟数、秒数和毫秒数

很快:

  • 将日期转换为总小时数
  • 从另一个数字中减去一个数字,然后使用Abs使其为正
  • 创建一个范围为1且结果为2的随机数。在上面
  • 将得到的随机小时数加回到两个日期中较早的日期

  • 首先,找出随机日期时间(小时、分钟、秒、毫秒等)的精度

    然后计算出该单元中两个日期之间的差异

    创建一个介于0和该差值之间的随机整数

    将以单位表示的随机整数添加到原始日期

    给定您上面提到的用例,计算for循环外部的差异


    在for循环中,获取随机整数并构造随机日期。

    以下是我的算法和代码:

    • 找出两个日期之间的差异
    • 对于每个迭代,在两个日期之间创建一个随机数
    • 在它们之间创建一个新日期。只需将该随机数作为分钟添加到开始日期时间

      Random randNum = new Random();
      
      DateTime minDt = new DateTime(2000,1,1,10,0,0);
      DateTime maxDt = new DateTime(2000,1,1,17,0,0);
      List<DateTime> myDates = new List<DateTime>();
      //Random.Next in .NET is non-inclusive to the upper bound (@NickLarsen)
      int minutesDiff = Convert.ToInt32(maxDt.Subtract(minDt).TotalMinutes+1);
      
      for (int i = 0; i < 100; i++)
      {
         // some random number that's no larger than minutesDiff, no smaller than 1
         int r=   randNum.Next(1, minutesDiff); 
         myDates.Add(minDt.AddMinutes(r));
      }
      
      foreach (DateTime d in myDates)
      {
        Console.WriteLine(string.Format("{0:dd-MMM-yyyy hh:mm}",d));
      }
      
      Random randNum=new Random();
      DateTime minDt=新的日期时间(2000,1,1,10,0,0);
      DateTime maxDt=新的日期时间(2000,1,1,17,0,0);
      List myDates=新列表();
      //NET中的Random.Next不包含上限(@NickLarsen)
      int minutesDiff=转换为32(最大减法(minDt).TotalMinutes+1);
      对于(int i=0;i<100;i++)
      {
      //一些不大于minutesDiff,不小于1的随机数
      int r=randNum.Next(1,分钟差);
      myDates.Add(minDt.AddMinutes(r));
      }
      foreach(日期时间d,以myDates为单位)
      {
      WriteLine(string.Format(“{0:dd-MMM-yyy-hh:mm}”,d));
      }
      

    这里有一种使用随机数的刻度的方法:

    Random r= new Random(); 
        //for better randomness don't recreate a new Random() too frequently.
    long rand62bit = (((long)r.Next())<<31) + r.Next(); 
        // 62bits suffices for random datetimes, 31 does not!
    DateTime newDate = startDate + new TimeSpan(rand62bit % (endDate - startDate).Ticks); 
    
    Random r=new Random();
    //为了获得更好的随机性,不要太频繁地重新创建新的Random()。
    
    long rand62bit=((long)r.Next())这就是我使用的:

    class RandomDates
    {
        private Random random = new Random();
    
        public DateTime Date(DateTime? start = null, DateTime? end = null)
        {
            if (start.HasValue && end.HasValue && start.Value >= end.Value)
                throw new Exception("start date must be less than end date!");
    
            DateTime min = start ?? DateTime.MinValue;
            DateTime max = end ?? DateTime.MaxValue;
    
            // for timespan approach see: http://stackoverflow.com/q/1483670/1698987
            TimeSpan timeSpan = max - min;
    
            // for random long see: http://stackoverflow.com/a/677384/1698987
            byte[] bytes = new byte[8];
            random.NextBytes(bytes);
    
            long int64 = Math.Abs(BitConverter.ToInt64(bytes, 0)) % timeSpan.Ticks;
    
            TimeSpan newSpan = new TimeSpan(int64);
    
            return min + newSpan;
        }
    }
    

    我在接受的答案中使用了这种方法,但由于有问题,我对其进行了轻微修改。

    基于ChrisF解决方案的一行程序

    var newDate = startDate.AddHours(new Random(Convert.ToInt32(DateTime.Now.Ticks / int.MaxValue)).Next(0, (int)(endDate - startDate).TotalHours));
    

    我刚刚给出了相同的答案,这时你的答案突然出现;)正试图将此评论附加到最后一篇文章中…记住,随机。下一个在.NET中是不包含上限的。另请参见Nod-这是重复的。我投票结束了我自己的问题:)该方法可能应该命名为
    DateTime
    ,而不是
    Date
    ——我脑子里有简单的日期,但它当然会返回一个
    DateTime
    。我只想说,这样的一行程序对代码的可读性没有好处。请避免在生产系统中使用这些。