How to create a list of random dates in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Module RandomDates

    ' Generate a random date between two years using Date
    Function RandomDate(startYear As Integer, endYear As Integer, rng As Random) As Date
        ' Convert start and end years to timestamps
        Dim startDate As New Date(startYear, 1, 1)
        Dim endDate As New Date(endYear, 12, 31)

        ' Uniform distribution over the timestamp range
        Dim rangeDays As Integer = CInt((endDate - startDate).TotalDays)
        Dim offset As Integer = rng.Next(0, rangeDays + 1)

        ' Convert back to Date
        Return startDate.AddDays(offset)
    End Function

    Sub Main()
        Dim rng As New Random() ' Seed RNG
        Dim dates As New List(Of Date)

        For i As Integer = 0 To 9
            dates.Add(RandomDate(1990, 2030, rng))
        Next

        For Each d As Date In dates
            Console.WriteLine($"{d.Year}-{d.Month}-{d.Day}")
        Next
    End Sub

End Module



' run:
'
' 2022-4-22
' 2019-5-8
' 2024-2-9
' 1990-6-19
' 2030-2-17
' 2026-8-12
' 2028-10-6
' 2006-6-10
' 2023-5-5
' 2007-9-5
'

 



answered 7 hours ago by avibootz
...