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#
?
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.
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.
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.
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?
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"
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With