Daniel Peñalba Daniel Peñalba - 1 month ago 5
C# Question

Convert milliseconds to human readable time lapse

I would like to format some commands execution times in a human readable format, for example:

3 -> 3ms
1100 -> 1s 100ms
62000 -> 1m 2s
etc ..


Taking into account days, hours, minutes, seconds, ...

Is it possible using
C#
?

Answer

You can use TimeSpan class, something like this:

TimeSpan t = TimeSpan.FromMilliseconds(ms);
string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", 
                        t.Hours, 
                        t.Minutes, 
                        t.Seconds, 
                        t.Milliseconds);

It's quite similar as this thread I've just found:

C#: What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?