C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: Arguments to the TimeSpan constructor are ordered from large stun it of time to smallest.
VB.NET program that uses constructor
Module Module1
Sub Main()
' Use the TimeSpan constructor to specify...
' ... days, hours, minutes, seconds, milliseconds.
Dim span As TimeSpan = New TimeSpan(1, 2, 0, 30, 0)
Console.WriteLine(span)
End Sub
End Module
Output
1.02:00:30
VB.NET program that uses From functions
Module Module1
Sub Main()
' Get TimeSpan instances from a specific unit of time.
Dim span1 As TimeSpan = TimeSpan.FromDays(1)
Dim span2 As TimeSpan = TimeSpan.FromHours(1)
Dim span3 As TimeSpan = TimeSpan.FromMinutes(1)
Dim span4 As TimeSpan = TimeSpan.FromSeconds(1)
Dim span5 As TimeSpan = TimeSpan.FromMilliseconds(1)
Console.WriteLine(span1)
Console.WriteLine(span2)
Console.WriteLine(span3)
Console.WriteLine(span4)
Console.WriteLine(span5)
End Sub
End Module
Output
1.00:00:00
01:00:00
00:01:00
00:00:01
00:00:00.0010000
VB.NET program that uses Add, Subtract
Module Module1
Sub Main()
' Input TimeSpans.
Dim span1 As TimeSpan = TimeSpan.FromMinutes(1)
Dim span2 As TimeSpan = TimeSpan.FromMinutes(2)
' Add.
Dim span3 As TimeSpan = span1.Add(span2)
Console.WriteLine(span3)
' Subtract.
Dim span4 As TimeSpan = span2.Subtract(span1)
Console.WriteLine(span4)
End Sub
End Module
Output
00:03:00
00:01:00
And: In many programs, you can use the TimeSpan.Zero constant as a default value for a TimeSpan.
VB.NET program that uses Max, Min and Zero
Module Module1
Sub Main()
' Maximum, minimum, zero values.
Console.WriteLine(TimeSpan.MaxValue)
Console.WriteLine(TimeSpan.MinValue)
Console.WriteLine(TimeSpan.Zero)
End Sub
End Module
Output
10675199.02:48:05.4775807
-10675199.02:48:05.4775808
00:00:00
VB.NET program that uses TicksPer constants
Module Module1
Sub Main()
' Display these constants.
Console.WriteLine(TimeSpan.TicksPerDay)
Console.WriteLine(TimeSpan.TicksPerHour)
Console.WriteLine(TimeSpan.TicksPerMinute)
Console.WriteLine(TimeSpan.TicksPerSecond)
Console.WriteLine(TimeSpan.TicksPerMillisecond)
End Sub
End Module
Output
864000000000
36000000000
600000000
10000000
10000
VB.NET program that uses Duration function
Module Module1
Sub Main()
' Convert this negative TimeSpan into a positive TimeSpan.
Dim span As TimeSpan = New TimeSpan(-1, -1, -1)
Dim duration As TimeSpan = span.Duration()
Console.WriteLine(duration)
End Sub
End Module
Output
01:01:01
Note: The other Total properties on TimeSpan follow this same pattern. They represent the total time, not just a unit of it.
VB.NET program that uses Hours and TotalHours
Module Module1
Sub Main()
' Compare Hours and TotalHours.
Dim span As TimeSpan = New TimeSpan(0, 500, 0, 0, 0)
Console.WriteLine(span.Hours)
Console.WriteLine(span.TotalHours)
End Sub
End Module
Output
20
500