G e t A c q u a i n t e d w i t h t h e T i m e S p a n C l a s s
By Michael McIntyre
The purpose of the System.TimeSpan object is to make it very easy to calculate elapsed time. Use it to calculate a period of time and extract the days, minutes, seconds, and milliseconds that have elapsed. Get acquainted with the TimeSpan class through examples in this article.
Example 1: TimeSpan Subtract Method
’ Declare two DateTime type variables.
’ startTime is set to 1/1/2003.
Dim startTime As DateTime = CType(“1/1/2003”, DateTime)
’ endTime is set to Now (current date and time).
Dim endTime As DateTime = System.DateTime.Now
’ Declare a variable of type TimeSpan named aTimeSpan.
’ Assign the result of subtracting startTime from endTime
’ to the aTimeSpan variable.
Dim aTimeSpan As System.TimeSpan = endTime.Subtract(startTime)
’ Report the time passed from 1/1/2003 to Now.
Console.WriteLine("Since " & startTime.ToShortDateString & " " & _
aTimeSpan.Days & " days, " & aTimeSpan.Hours & " hours have passed.")
Result: Since 1/1/2003 254 days, 15 hours have passed.
Example 2: Time Clock
’ Declare two DateTime type variables to represent
’ clock in and clock out times.
’ Set clockInTime to 12:30:01 PM 8/12/2003.
Dim clockInTime As DateTime = CType(“08/12/2003 12:30:01 PM”, DateTime)
’ Set clockOutTime to 01:30:26 PM 8/13/2003.
Dim clockOutTime As DateTime = CType(“08/13/2003 01:30:26 AM”, DateTime)
’ Declare a variable of type TimeSpan named aTimeSpan.
’ Assign the result of subtracting clockInTime from clockOutTime
’ to the aTimeSpan variable.
Dim aTimeSpan As System.TimeSpan = clockOutTime.Subtract(clockInTime)
’ Report clockInTime and clockOutTime.
Console.WriteLine("Clocked in at " & clockInTime.ToString & vbCrLf & _
"Clocked out at " & clockOutTime & vbCrLf)
’ Report time worked.
Console.WriteLine(“Worked " & aTimeSpan.Days & " days,” & _
aTimeSpan.Hours & " hours, and " & aTimeSpan.Minutes & " minutes.")
Result: Worked 0 days,13 hours, and 0 minutes.
Example 3: TimeSpan FromMilliseconds Method
’ Declare a variable of type TimeSpan named aTimeSpan.
Dim aTimeSpan As TimeSpan
’ Call the TimeSpan FromMilliseconds method passing in
’ the System.Environment.TickCount (milliseconds since last boot).
’ Assign the result to aTimeSpan.
aTimeSpan = TimeSpan.FromMilliseconds(System.Environment.TickCount)
’ Report the time since the computer was last booted.
Console.WriteLine("Since your computer’s last boot " & _
aTimeSpan.Days & " days," & aTimeSpan.Hours & " hours, and " _
& aTimeSpan.Minutes & " minutes have passed.")
Result: Since your computer’s last boot 0 days,9 hours, and 42 minutes have passed.
The article has provided a basic introduction to the TimeSpan class. To learn more about the other members of the TimeSpan class click here.