Mohanapriya R Mohanapriya R
Updated date May 02, 2024
In this article, we will explore TimeSpan conversion in C#. Learn how to convert time intervals into strings, using default methods and custom formats.

Default TimeSpan.ToString():

This method returns a string representation of the TimeSpan in the format "d.hh:mm:ss".

TimeSpan timeSpan = new TimeSpan(3, 14, 30, 45);
string defaultString = timeSpan.ToString();
Console.WriteLine($"Default ToString(): {defaultString}");


Default ToString(): 3.14:30:45

Custom Format Strings:

You can use custom format strings to control the output format precisely. For example, "hh:mm:ss" will display only hours, minutes, and seconds.

string customFormat = timeSpan.ToString("hh\\:mm\\:ss");
Console.WriteLine($"Custom Format: {customFormat}");


Custom Format: 14:30:45

String Interpolation:

Utilize string interpolation for a more dynamic approach. This allows you to embed TimeSpan directly within a string.

string interpolatedString = $"TimeSpan: {timeSpan}";


TimeSpan: 3.14:30:45

Comments (0)

There are no comments. Be the first to comment!!!