TimeSpan to Custom string like HH:mm:ss

DmitryBoyko picture DmitryBoyko · Jul 9, 2016 · Viewed 22.9k times · Source

I would like to convert

var delta = TimeSpan.FromSeconds(10);

to string like 00:00:01

I try this delta.ToString(@"0:\\hh\\:mm\\:ss", System.Globalization.CultureInfo.InvariantCulture);

But nothing is working fine. Also I cannot find here https://msdn.microsoft.com/en-us/library/ee372287.aspx correct way to do it.

Method ToString() does not help so i need in format lie hh:mm:ss.

enter image description here Any clue?

Answer

ManoDestra picture ManoDestra · Jul 9, 2016

Just use the ToString(String format) method of TimeSpan, passing in the format you require.

https://msdn.microsoft.com/en-us/library/dd992632(v=vs.110).aspx

E.g.

var ts = TimeSpan.FromMinutes(10000);
var output = ts.ToString(@"hh\:mm\:ss");
Console.WriteLine(output);