Imports System
Public Class Program
Public Shared Function RelativePastTime(ByVal userdate As DateTime) As String
Const SECOND As Integer = 1
Const MINUTE As Integer = 60 * SECOND
Const HOUR As Integer = 60 * MINUTE
Const DAY As Integer = 24 * HOUR
Const MONTH As Integer = 30 * DAY
Dim ts = New TimeSpan(DateTime.UtcNow.Ticks - userdate.Ticks)
Dim delta As Double = Math.Abs(ts.TotalSeconds)
If delta < 1 * MINUTE Then
Return If(ts.Seconds = 1, "one second ago", ts.Seconds & " seconds ago")
End If
If delta < 2 * MINUTE Then
Return "a minute ago"
End If
If delta < 45 * MINUTE Then
Return ts.Minutes & " minutes ago"
End If
If delta < 90 * MINUTE Then
Return "an hour ago"
End If
If delta < 24 * HOUR Then
Return ts.Hours & " hours ago"
End If
If delta < 48 * HOUR Then
Return "yesterday"
End If
If delta < 30 * DAY Then
Return ts.Days & " days ago"
End If
If delta < 12 * MONTH Then
Dim months As Integer = Convert.ToInt32(Math.Floor(CDbl(ts.Days) / 30))
Return If(months <= 1, "one month ago", months & " months ago")
Else
Dim years As Integer = Convert.ToInt32(Math.Floor(CDbl(ts.Days) / 365))
Return If(years <= 1, "one year ago", years & " years ago")
End If
End Function
Public Shared Sub Main(ByVal args As String())
Console.WriteLine(DateTime.UtcNow)
Console.WriteLine("A: " & RelativePastTime(New DateTime(2024, 04, 23, 00, 00, 00)))
Console.WriteLine("B: " & RelativePastTime(New DateTime(2024, 04, 24, 00, 00, 00)))
Console.WriteLine("C: " & RelativePastTime(New DateTime(2024, 03, 25, 00, 00, 00)))
Console.WriteLine("D: " & RelativePastTime(New DateTime(2024, 04, 25, 17, 15, 00)))
Console.WriteLine("E: " & RelativePastTime(New DateTime(2024, 04, 25, 00, 15, 00)))
Console.WriteLine("F: " & RelativePastTime(New DateTime(2024, 04, 26, 07, 02, 30)))
Console.WriteLine("G: " & RelativePastTime(New DateTime(2023, 04, 25, 00, 00, 00)))
Console.WriteLine("H: " & RelativePastTime(New DateTime(2024, 04, 26, 07, 05, 03)))
End Sub
End Class
' run:
'
' 4/26/2024 7:04:35 AM
' A: 3 days ago
' B: 2 days ago
' C: one month ago
' D: 13 hours ago
' E: yesterday
' F: 2 minutes ago
' G: one year ago
' H: 32 seconds ago
'