Caculate DateTime By TimeSpan Class

Posted by dragon on Saturday, 10 September 2011

type='html'>A TimeSpan object represents a time interval, or duration of time, measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The largest unit of time used to measure duration is a day. Time intervals are measured in days for consistency because the number of days in larger units of time, such as months and years, varies.

Sample Code

Dim dFirstDate As DateTime = DateTime.Now

' Add day
Dim dLastDate As DateTime = DateTime.Now.AddDays(15)

' Subtract DateTime
Dim pTimeSpan As TimeSpan = dLastDate.Subtract(dFirstDate)

' Subtract DateTime Output
Console.WriteLine("Days : " & pTimeSpan.TotalDays)
Console.WriteLine("Hours : " & pTimeSpan.TotalHours)
Console.WriteLine("Minutes : " & pTimeSpan.TotalMinutes)
Console.WriteLine("Seconds : " & pTimeSpan.TotalSeconds)

' Compare DateTime
Dim nResult As Integer = DateTime.Compare(dLastDate, dFirstDate)
If nResult = 0 Then
Console.WriteLine("First date is equals to Last date")
ElseIf nResult > 0 Then
Console.WriteLine("First date is lesser than the Last date")
Else
Console.WriteLine("First date is greater than Last date")
End If

{ 0 comments... read them below or add one }

Post a Comment