Visual Basic:在 DatePicker 上选择随机日期

Visual Basic: Pick random date on a DatePicker

我有一个具有 MinDateMaxDate 值的 DatePicker。 我可以将 DatePicker 的值随机化为 MinDate、MaxDate 或两者之间的任何日期吗?

DatePicker 上有简单的随机化功能吗?

谢谢! 巴特

'Random number generator.
Private rng As New Random

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    DateTimePicker1.Value = GetRandomDate(DateTimePicker1.MinDate, DateTimePicker1.MaxDate)
End Sub

Private Function GetRandomDate(minDate As Date, maxDate As Date) As Date
    'Get the number of days between the date limits.
    Dim dayCount = (maxDate - minDate).Days

    'Get a random number in the range zero to dayCount.
    'NOTE: The upper limit for Next is exclusive, so add 1 to dayCount.
    Dim dayOffset = rng.Next(dayCount + 1)

    'Add the random offset to the minimum date to get the final date.
    Return minDate.AddDays(dayOffset)
End Function

您可以使用控件的最大和最小可分配值之间的 Ticks 计数,乘以一个随机值并将结果值添加到最小值。

在 WinForm 的 DateTimePicker 中,可分配给控件的最小值和最大值在 DateTimePicker.MaxDate and DateTimePicker.MinDate 属性中指定。

Random class can be used to generate a random Double value in the range [0.00 - 1.00) using its NextDouble() 方法。

► 您应该将随机生成器声明为 static (Shared) 字段,然后在需要时调用其方法。

然后您可以从生成的随机值创建一个 TimeSpan - 转换为 Long - 并将 TimeSpan 添加到控件的 MinDate(或使用 DateTime.AddTicks() 方法) .
这会随机化日期和时间部分:

Private Shared rndDate As New Random()
' [...]

' Call when needed
Dim dtPicker = [Some DateTimePicker instance]
Dim randomTicks = CLng((dtPicker.MaxDate - dtPicker.MinDate).Ticks * rndDate.NextDouble())
dtPicker.Value = dtPicker.MinDate + New TimeSpan(randomTicks) 
' OR dtPicker.Value = dtPicker.MinDate + TimeSpan.FromTicks(randomTicks)
' OR dtPicker.Value = dtPicker.MinDate.AddTicks(randomTicks)