Convert a TimeSpan to a formatted string in C#
This post will discuss how to convert a TimeSpan object to a formatted string in C#.
A TimeSpan object represents a time interval unrelated to a particular date. It differs from the DateTime object, which represents both date and time values.
We can get a TimeSpan object by subtracting two DateTime objects in C#. The following example prints a TimeSpan object.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; public class Example { public static void Main() { DateTime now = DateTime.Now; DateTime then = new DateTime(2017, 12, 25); TimeSpan ts = now - then; Console.WriteLine("The time difference is: {0}", ts.ToString()); } } /* Output: The time difference is: 743.20:24:39.5120760 */ |
To do formatting of a TimeSpan object, use TimeSpan.ToString() method. Have a look at the Microsoft Documentation on TimeSpan custom format strings for more information.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; public class Example { public static void Main() { DateTime now = DateTime.Now; DateTime then = DateTime.Now.AddHours(-2).AddMinutes(-30); TimeSpan ts = now - then; string format = @"dd\:hh\:mm\:ss\.fffffff"; Console.WriteLine("The time difference is: {0}", ts.ToString(format)); } } /* Output: The time difference is: 00:02:29:59.9991998 */ |
The TimeSpan object exposes its members to return the total number of days, hours, minutes, seconds, and fractions of a second. The following example displays properties of a TimeSpan object that represents the difference between two dates.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; public class Example { public static void Main() { DateTime now = DateTime.Now; DateTime then = new DateTime(2017, 12, 25); TimeSpan ts = now - then; Console.WriteLine(@"{0} Days, {1} Hours, {2} Minutes, {3} Seconds and {4} Milliseconds", ts.Days, ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds); } } /* Output: 743 Days, 20 Hours, 26 Minutes, 15 Seconds and 84 Milliseconds */ |
That’s all about converting a TimeSpan to a formatted string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)