Convert milliseconds to human readable time lapse

2020-05-19 03:43发布

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

10条回答
ゆ 、 Hurt°
2楼-- · 2020-05-19 04:23

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'
查看更多
该账号已被封号
3楼-- · 2020-05-19 04:23

For example to get 00:01:35.0090000 as 0 hours, 1 minutes, 35 seconds and 9 milliseconds you can use this:

Console.WriteLine("Time elapsed:" +TimeSpan.FromMilliseconds(numberOfMilliseconds).ToString());

Your output:

Time elapsed: 00:01:35.0090000
查看更多
劳资没心,怎么记你
4楼-- · 2020-05-19 04:25

Well i normally hate writing if statements but some times what you really have is a nail and need a hammer.

string time;
if (elapsedTime.TotalMinutes > 2)
    time = string.Format("{0:n2} minutes", elapsedTime.TotalMinutes);
else if (elapsedTime.TotalSeconds > 15)
    time = string.Format("{0:n2} seconds", elapsedTime.TotalSeconds);
else
    time = string.Format("{0:n0}ms", elapsedTime.TotalMilliseconds);
查看更多
Emotional °昔
5楼-- · 2020-05-19 04:27

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?

查看更多
登录 后发表回答