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}");
Output:
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}");
Output:
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}";
Console.WriteLine(interpolatedString);
Output:
TimeSpan: 3.14:30:45
Comments (0)