How to find the difference between two random future dates in VB.NET

1 Answer

0 votes
Imports System

Module Program

    '
    ' Generates a random future date by adding a random number of days
    ' to today's date. The range is controlled by minDays and maxDays.
    '
    Function GenerateRandomFutureDate(minDays As Integer, maxDays As Integer, rng As Random) As DateTime
        Dim randomOffset As Integer = rng.Next(minDays, maxDays + 1)   ' random number of days
	
        Return DateTime.Now.AddDays(randomOffset).Date                 ' convert to date-only
    End Function

    '
    ' Calculates the difference between two dates and returns a TimeSpan.
    '
    Function CalculateDateDifference(date1 As DateTime, date2 As DateTime) As TimeSpan
        Return date2 - date1
    End Function

    Sub Main()
        Dim rng As New Random()   ' random number generator

        ' Create two random future dates
        Dim date1 As DateTime = GenerateRandomFutureDate(10, 40, rng)   ' between 10–40 days from now
        Dim date2 As DateTime = GenerateRandomFutureDate(20, 60, rng)   ' between 20–60 days from now

        ' Calculate the difference
        Dim difference As TimeSpan = CalculateDateDifference(date1, date2)

        ' Display results
        Console.WriteLine("Random Future Date 1: " & date1.ToShortDateString())
        Console.WriteLine("Random Future Date 2: " & date2.ToShortDateString())
        Console.WriteLine("Difference in days: " & difference.Days)
    End Sub

End Module


'
' run1: 
'
' Random Future Date 1: 05/25/2026
' Random Future Date 2: 06/28/2026
' Difference in days: 34
'
' run2:
'
' Random Future Date 1: 06/22/2026
' Random Future Date 2: 06/17/2026
' Difference in days: -5
'

 



answered 5 hours ago by avibootz
...