C# 将毫秒转换为人类可读的延时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9993883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert milliseconds to human readable time lapse
提问by Daniel Pe?alba
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#?
可以使用C#吗?
采纳答案by walther
You can use TimeSpan class, something like this:
您可以使用 TimeSpan 类,如下所示:
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?
回答by Arion
Maybe something like this?
也许是这样的?
DateTime.Now.ToString("%d 'd' %h 'h' %m 'm' %s 'seconds' %ms 'ms'")
回答by Nuffin
You could utilize the static TimeSpan.FromMillisecondsmethod as well as the resulting TimeSpan's Days, Hours, Minutes, Secondsand Millisecondsproperties.
你可以使用静态TimeSpan.FromMilliseconds方法,以及由此产生TimeSpan的Days,Hours,Minutes,Seconds和Milliseconds属性。
But I'm busy right now, so I'll leave the rest to you as an exercise.
不过我现在很忙,剩下的就留给你练习吧。
回答by hungryMind
.NET 4 accepts format in TimeSpan.Tostring().
.NET 4 接受TimeSpan.Tostring().
For other you can implement extension method like
对于其他人,您可以实现扩展方法,如
public static string Format(this TimeSpan obj)
{
StringBuilder sb = new StringBuilder();
if (obj.Hours != 0)
{
sb.Append(obj.Hours);
sb.Append(" ");
sb.Append("hours");
sb.Append(" ");
}
if (obj.Minutes != 0 || sb.Length != 0)
{
sb.Append(obj.Minutes);
sb.Append(" ");
sb.Append("minutes");
sb.Append(" ");
}
if (obj.Seconds != 0 || sb.Length != 0)
{
sb.Append(obj.Seconds);
sb.Append(" ");
sb.Append("seconds");
sb.Append(" ");
}
if (obj.Milliseconds != 0 || sb.Length != 0)
{
sb.Append(obj.Milliseconds);
sb.Append(" ");
sb.Append("Milliseconds");
sb.Append(" ");
}
if (sb.Length == 0)
{
sb.Append(0);
sb.Append(" ");
sb.Append("Milliseconds");
}
return sb.ToString();
}
and call as
并称为
foreach (TimeSpan span in spans)
{
MessageBox.Show(string.Format("{0}", span.Format()));
}
回答by Igor Korkhov
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'
回答by Ian Becker
I know this is old, but I wanted to answer with a great nuget package.
我知道这很旧,但我想用一个很棒的 nuget 包来回答。
Install-Package Humanizer
https://www.nuget.org/packages/Humanizer
https://www.nuget.org/packages/Humanizer
https://github.com/MehdiK/Humanizer
https://github.com/MehdiK/Humanizer
Example from their readme.md
来自他们的 readme.md 的例子
TimeSpan.FromMilliseconds(1299630020).Humanize(4) => "2 weeks, 1 day, 1 hour, 30 seconds"
回答by Chris Marisic
Well i normally hate writing if statements but some times what you really have is a nail and need a hammer.
好吧,我通常讨厌写 if 语句,但有时您真正拥有的是钉子,需要锤子。
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);
回答by Hassen Ch.
For example to get 00:01:35.0090000as 0 hours, 1 minutes, 35 seconds and 9 milliseconds you can use this:
例如,要获得00:01:35.00900000 小时、1 分钟、35 秒和 9 毫秒,您可以使用:
Console.WriteLine("Time elapsed:" +TimeSpan.FromMilliseconds(numberOfMilliseconds).ToString());
Your output:
你的输出:
Time elapsed: 00:01:35.0090000
回答by Sedat Gokalp
public static string ReadableTime(int milliseconds)
{
var parts = new List<string>();
Action<int, string> add = (val, unit) => { if (val > 0) parts.Add(val+unit); };
var t = TimeSpan.FromMilliseconds(milliseconds);
add(t.Days, "d");
add(t.Hours, "h");
add(t.Minutes, "m");
add(t.Seconds, "s");
add(t.Milliseconds, "ms");
return string.Join(" ", parts);
}
回答by mike
This probably has a slightly different output than requested, but the result is human readable - and it can be adapted to fit many other use cases.
这可能与请求的输出略有不同,但结果是人类可读的 - 它可以适应许多其他用例。
private static List<double> _intervals = new List<double>
{
1.0 / 1000 / 1000,
1.0 / 1000,
1,
1000,
60 * 1000,
60 * 60 * 1000
};
private static List<string> _units = new List<string>
{
"ns",
"μs",
"ms",
"s",
"min",
"h"
};
public string FormatUnits(double milliseconds, string format = "#.#")
{
var interval = _intervals.Last(i=>i<=milliseconds);
var index = _intervals.IndexOf(interval);
return string.Concat((milliseconds / interval).ToString(format) , " " , _units[index]);
}
Example calls...
示例调用...
Console.WriteLine(FormatUnits(1));
Console.WriteLine(FormatUnits(20));
Console.WriteLine(FormatUnits(300));
Console.WriteLine(FormatUnits(4000));
Console.WriteLine(FormatUnits(50000));
Console.WriteLine(FormatUnits(600000));
Console.WriteLine(FormatUnits(7000000));
Console.WriteLine(FormatUnits(80000000));
...and results:
...和结果:
1000 μs
20 ms
300 ms
4 s
50 s
10 min
1.9 h
22.2 h

