C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: We can use the user interface in Visual Studio to easily choose the best one.
Program: We call the TimeSpan constructor with 5 int arguments. The code creates a TimeSpan with 1 day, 2 hours, and 30 seconds.
C# program that uses TimeSpan constructor
using System;
class Program
{
static void Main()
{
// Use TimeSpan constructor to specify:
// ... Days, hours, minutes, seconds, milliseconds.
// ... The TimeSpan returned has those values.
TimeSpan span = new TimeSpan(1, 2, 0, 30, 0);
Console.WriteLine(span);
}
}
Output
1.02:00:30
Double: These methods convert a number of double type into a TimeSpan struct instance.
Result: The TimeSpan result will allow you to use the figure in a more natural way in C# programs and other methods.
Tip: It is useful to pass a number that has a decimal place to the From methods.
Convert TimeSpan, LongC# program that uses TimeSpan.From methods
using System;
class Program
{
static void Main()
{
// Get time spans from a specific double unit of time.
// ... These allow easier manipulation of the time.
TimeSpan span1 = TimeSpan.FromDays(1);
TimeSpan span2 = TimeSpan.FromHours(1);
TimeSpan span3 = TimeSpan.FromMinutes(1);
TimeSpan span4 = TimeSpan.FromSeconds(1);
TimeSpan span5 = TimeSpan.FromMilliseconds(1);
Console.WriteLine(span1);
Console.WriteLine(span2);
Console.WriteLine(span3);
Console.WriteLine(span4);
Console.WriteLine(span5);
}
}
Output
1.00:00:00
01:00:00
00:01:00
00:00:01
00:00:00.0010000
Immutable: Structs such as TimeSpan are immutable and you can assign the result of the Add method to another TimeSpan variable.
StructC# program that uses TimeSpan.Add method
using System;
class Program
{
static void Main()
{
// Adds a TimeSpan of one minute to a TimeSpan of two minutes.
// ... Then we get three minutes in a TimeSpan.
TimeSpan span1 = TimeSpan.FromMinutes(1);
TimeSpan span2 = TimeSpan.FromMinutes(2);
TimeSpan span3 = span1.Add(span2);
Console.WriteLine(span3);
}
}
Output
00:03:00
Next: This program shows that when you subtract one second from one minute, you receive 59 seconds.
C# program that uses TimeSpan.Subtract method
using System;
class Program
{
static void Main()
{
// Subtract TimeSpan of one second from one minute.
// ... The result is 59 seconds.
TimeSpan span1 = TimeSpan.FromMinutes(1);
TimeSpan span2 = TimeSpan.FromSeconds(1);
TimeSpan span3 = span1.Subtract(span2);
Console.WriteLine(span3);
}
}
Output
00:00:59
Note: The MaxValue is equal to over ten million days. The MinValue is equal to negative ten million days.
C# program that uses MaxValue and MinValue
using System;
class Program
{
static void Main()
{
// Write the maximum, minimum and zero values for TimeSpan.
Console.WriteLine(TimeSpan.MaxValue);
Console.WriteLine(TimeSpan.MinValue);
Console.WriteLine(TimeSpan.Zero);
}
}
Output
10675199.02:48:05.4775807
-10675199.02:48:05.4775808
00:00:00
Note: These are constants and can be accessed with the composite name of the TimeSpan type.
constTip: The constants show how many ticks occur in each of these normal time units. There are 10,000 ticks in one millisecond.
C# program that uses TicksPer constants
using System;
class Program
{
static void Main()
{
// Write the values for these Ticks Per constants.
Console.WriteLine(TimeSpan.TicksPerDay);
Console.WriteLine(TimeSpan.TicksPerHour);
Console.WriteLine(TimeSpan.TicksPerMinute);
Console.WriteLine(TimeSpan.TicksPerSecond);
Console.WriteLine(TimeSpan.TicksPerMillisecond);
}
}
Output
864000000000
36000000000
600000000
10000000
10000
Negative: If you have a negative TimeSpan, this method will make the TimeSpan positive.
C# program that uses Duration method
using System;
class Program
{
static void Main()
{
// Use the TimeSpan Duration method.
// ... This converts negative TimeSpans into positive TimeSpans.
// ... Same as absolute value of the time.
TimeSpan span = new TimeSpan(-1, -1, -1);
TimeSpan duration = span.Duration();
Console.WriteLine(duration);
}
}
Output
01:01:01
Note: This also applies to other properties such as Seconds and TotalSeconds, and Days and TotalDays.
Hours: The Hours property returns the component of the TimeSpan that indicates hours. This is only a part of the entire time represented.
TotalHours: The TotalHours property returns the entire time represented converted to a value represented in hours.
C# program that uses Hours and TotalHours
using System;
class Program
{
static void Main()
{
// Shows the TimeSpan constructor, Hours and TotalHours.
// ... Hours is only a part of the time.
// ... TotalHours converts the entire time to hours.
TimeSpan span = new TimeSpan(0, 500, 0, 0, 0);
Console.WriteLine(span.Hours);
Console.WriteLine(span.TotalHours);
}
}
Output
20
500
C# program that uses TimeSpan.Zero value
using System;
class Program
{
static void Main()
{
// Demonstrate TimeSpan zero.
TimeSpan span = TimeSpan.Zero;
Console.WriteLine(span);
Console.WriteLine(span.TotalMilliseconds);
}
}
Output
00:00:00
0
Note: Internally, the TimeSpan.Zero field is initialized in a static constructor in the TimeSpan type.
Tip: It uses the TimeSpan constructor where the argument is a long value of ticks. The argument 0L is used. This is zero in long format.
Also: In the TimeSpan(long) constructor, the field of name "_ticks" is assigned to the parameter. TimeSpan.Zero equals "new TimeSpan(0)".
TimeSpan constructor: C#
static TimeSpan()
{
Zero = new TimeSpan(0L);
MaxValue = new TimeSpan(9223372036854775807L);
MinValue = new TimeSpan(-9223372036854775808L);
}
But: TryParse is safer and faster for when you may encounter errors in the data, and it is usually better to use for this case.
First: This program first parses an entirely valid time span string. It specifies a span with zero hours, zero minutes, and one second.
Also: The program uses TryParse on an invalid time span string. This causes no exception to be thrown.
C# program that uses Parse and TryParse on TimeSpan
using System;
class Program
{
static void Main()
{
// Use TimeSpan.Parse method to parse in span string.
// ... Write it to the console.
TimeSpan span = TimeSpan.Parse("0:00:01");
Console.WriteLine(span);
// Use TimeSpan.TryParse to try to parse an invalid span.
// ... The result is TimeSpan.Zero.
TimeSpan span2;
TimeSpan.TryParse("X:00:01", out span2);
Console.WriteLine(span2);
}
}
Output
00:00:01
00:00:00
Here: We create a TimeSpan of 3 hours, 30 minutes. We format it with an hours: minutes: seconds format.
ToString: We can use these format strings in ToString, Console.WriteLine and string.Format.
C# program that uses format string
using System;
class Program
{
static void Main()
{
// Represents three hours and thirty minutes.
TimeSpan threeHours = new TimeSpan(3, 30, 0);
// Write hours, minutes and seconds.
Console.WriteLine("{0:hh\\:mm\\:ss}", threeHours);
}
}
Output
03:30:00
Version 1: In this version of the code we create a new TimeSpan with its FromHours method.
Version 2: Here we use the TimeSpan constructor with 3 arguments to create a new TimeSpan instance.
Version 3: This code does not create a new TimeSpan but assumes a cached TimeSpan is available and references that.
Result: The code that uses TimeSpan.FromHours is far slower than the other 2 examples.
C# program that benchmarks TimeSpan
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
const int m = 100000000;
Stopwatch s1 = Stopwatch.StartNew();
// Version 1: use FromHours.
for (int i = 0; i < m; i++)
{
TimeSpan span = TimeSpan.FromHours(1);
}
s1.Stop();
Stopwatch s2 = Stopwatch.StartNew();
// Version 2: use TimeSpan constructor.
for (int i = 0; i < m; i++)
{
TimeSpan span = new TimeSpan(1, 0, 0);
}
s2.Stop();
Stopwatch s3 = Stopwatch.StartNew();
// Version 3: use cached TimeSpan.
TimeSpan cache = new TimeSpan(1, 0, 0);
for (int i = 0; i < m; i++)
{
TimeSpan span = cache;
}
s3.Stop();
Console.WriteLine("{0},{1},{2}", s1.ElapsedMilliseconds,
s2.ElapsedMilliseconds, s3.ElapsedMilliseconds);
Console.Read();
}
}
Output
TimeSpan.FromHours(1): 1788 ms
new TimeSpan(1, 0, 0): 989 ms
Cache: 31 ms
Note: TimeSpan.FromHours has these instructions: 1 check, 1 multiply, 1 add, 1 check, 2 checks, 1 multiply, 1 cast, 1 constructor.
Tip: You can improve performance when using TimeSpan instances. When using dates and times, cache TimeSpans you will repeatedly need.
Avoid these TimeSpan methods:
TimeSpan.FromDays
TimeSpan.FromHours
TimeSpan.FromMilliseconds
TimeSpan.FromMinutes
TimeSpan.FromSeconds
Prefer these TimeSpan constructors:
new TimeSpan(long)
new TimeSpan(int, int int)