'How to convert a string to TimeSpan in format "HH:mm:ss"

In my code i have this:

string myString;
TimeSpan? myTimeSpan;

myString = myTimeSpan.ToString("HH:mm:ss")

I got the error no overload for method 'ToString' takes 1 arguments.

I want convert TimeSpan to string in format HH:mm:ss.



Solution 1:[1]

First problem: you use a Nullable<TimeSpan>, so you need to use it's Value property,


TimeSpan.ToString does not support all format strings that DateTime.ToString supports.

You need to escape the ::

Console.Write(System.DateTime.Now.TimeOfDay.ToString("hh\\:mm\\:ss"));

Demo: https://dotnetfiddle.net/uIMqW0

Read: Custom TimeSpan format strings

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1