One of my colleague asked me how to get the relative time for the given datetime. Some thing like
- less than a minute ago
- about a minute ago
- 10 minutes ago
- 1 hour ago
- 5 days ago
Here is the a VB.Net source code which will provide the relative time for the given date:
Instructions:
- Open a New Console application
- Add a new bas module called Module1
- Copy the following code to Module1 bas module
Module Module1
Sub Main()
Console.WriteLine(GetRelativeTime("6/3/2011 23:00:51"))
Console.WriteLine("Hit enter to exit...")
Console.ReadLine()
End Sub
Private Function GetRelativeTime(ByVal dt As Date) As String
Dim Diff As Long = DateDiff(DateInterval.Second, dt, Now)
Select Case Diff
Case Is < 60
Return "less than a minute ago"
Case Is < 120
Return "about a minute ago"
Case Is < 2700
Return String.Format("{0} minutes ago", Int(Diff / 60))
Case Is < 5400
Return "about an hour ago"
Case Is < 86400
Return String.Format("{0} hours ago", Int(Diff / 3600))
Case Is < 172800
Return "about 1 day ago"
Case Else
Return String.Format("{0} days ago", Int(Diff / 86400))
End Select
End Function
End ModuleProject Type: Console
Language: VB.Net
Tested with: VS 2010
DotNet Framework: 2.0
