Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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#?

like image 280
Daniel Peñalba Avatar asked Apr 03 '12 13:04

Daniel Peñalba


People also ask

How do you convert milliseconds to time?

To convert a second measurement to a millisecond measurement, multiply the time by the conversion ratio. The time in milliseconds is equal to the seconds multiplied by 1,000.

How do you convert milliseconds to hours and minutes?

To convert milliseconds to hours and minutes:Divide the milliseconds by 1000 to get the seconds. Divide the seconds by 60 to get the minutes. Divide the minutes by 60 to get the hours.

How do you convert MS to minutes and seconds?

Convert Milliseconds to minutes using the formula: minutes = (milliseconds/1000)/60). Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60). The print output from Milliseconds to minutes and seconds.


4 Answers

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:

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

like image 76
walther Avatar answered Oct 17 '22 00:10

walther


I know this is old, but I wanted to answer with a great nuget package.

Install-Package Humanizer

https://www.nuget.org/packages/Humanizer

https://github.com/MehdiK/Humanizer

Example from their readme.md

TimeSpan.FromMilliseconds(1299630020).Humanize(4) => "2 weeks, 1 day, 1 hour, 30 seconds"
like image 31
Ian Becker Avatar answered Oct 17 '22 01:10

Ian Becker


You could utilize the static TimeSpan.FromMilliseconds method as well as the resulting TimeSpan's Days, Hours, Minutes, Seconds and Milliseconds properties.

But I'm busy right now, so I'll leave the rest to you as an exercise.

like image 17
Nuffin Avatar answered Oct 17 '22 01:10

Nuffin


What about this?

var ts = TimeSpan.FromMilliseconds(86300000 /*whatever */);
var parts = string
                .Format("{0:D2}d:{1:D2}h:{2:D2}m:{3:D2}s:{4:D3}ms",
                    ts.Days, ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds)
                .Split(':')
                .SkipWhile(s => Regex.Match(s, @"00\w").Success) // skip zero-valued components
                .ToArray();
var result = string.Join(" ", parts); // combine the result

Console.WriteLine(result);            // prints '23h 58m 20s 000ms'
like image 17
Igor Korkhov Avatar answered Oct 17 '22 01:10

Igor Korkhov