以亂數進行某段日期區間的抽樣【延伸】

以亂數進行某段日期區間的抽樣【延伸】

上一篇(以亂數進行某段日期區間的抽樣)談到如何隨機進行某段日期區間的抽樣,有網友提到筆者的範例程式碼只能輸入整數小時(例如08:00),為了提供更彈性的函數,筆者將GetRandomDate做了一個這樣的多型,程式碼如下:

   1:  /// <summary>
   2:  /// 亂數進行日期抽樣
   3:  /// </summary>
   4:  /// <param name="StartDate">起始日期</param>
   5:  /// <param name="DueDate">結束日期</param>
   6:  /// <param name="StartHour">每日起始時間(時)</param>
   7:  /// <param name="DueHour">每日結束時間(時)</param>
   8:  /// <param name="StartMinutes">每日起始時間(分)</param>
   9:  /// <param name="DueMinutes">每日結束時間(分)</param>
  10:  /// <param name="count">抽樣數量</param>
  11:  /// <returns></returns>
  12:  private static List<DateTime> GetRandomDate(DateTime StartDate, DateTime DueDate, int StartHour
  13:      ,int StartMinutes, int DueHour, int DueMinutes,int count)
  14:  {
  15:      List<DateTime> list = new List<DateTime>();
  16:      DateTime dtStart = StartDate.AddHours(StartHour).AddMinutes(StartMinutes);
  17:      DateTime dtDue = DueDate.AddHours(DueHour).AddMinutes(DueMinutes);
  18:  
  19:      if (!(dtStart.CompareTo(dtDue) > 0 || count < 0))
  20:      {
  21:          Random ran = new Random();
  22:          while (list.Count < count)
  23:          {
  24:              DateTime dtCurrent = dtStart.AddDays(ran.Next(0
  25:                                                   , int.Parse(DueDate.Subtract(StartDate).TotalDays.ToString()) - 1));
  26:              dtCurrent = dtCurrent.AddMinutes(ran.Next(0, int.Parse(Math.Round(dtDue.Subtract(dtStart).TotalMinutes, 0).ToString()) - 1));
  27:  
  28:              DateTime dtLimitStart = new DateTime(dtCurrent.Year, dtCurrent.Month, dtCurrent.Day, StartHour, StartMinutes,0);
  29:              DateTime dtLimitEnd = new DateTime(dtCurrent.Year, dtCurrent.Month, dtCurrent.Day, DueHour, DueMinutes, 0);
  30:              if (dtCurrent.CompareTo(dtDue) < 1 && !list.Contains(dtCurrent) 
  31:                  && dtCurrent.CompareTo(dtLimitStart) >= 0 && dtCurrent.CompareTo(dtLimitEnd) <= 0)
  32:              {
  33:                  list.Add(dtCurrent);
  34:              }
  35:          }
  36:      }
  37:      return list;
  38:  }

以下範例示範從2011/7/20 08:31至2011/07/30 12:05這段區間隨機抽樣出20個樣本:

   1:  List<DateTime> list = GetRandomDate(new DateTime(2011, 7, 20)
   2:                                      , new DateTime(2011, 7, 30)
   3:                                      , 8, 31, 12, 5, 20);
   4:  foreach (DateTime dt in list)
   5:  {
   6:  Console.WriteLine(dt.ToString("yy-MM-dd hh:mm"));
   7:  }

 

執行結果:

image

 

參考資料:

DateTime.CompareTo 方法 (DateTime)