Convert milliseconds to human readable time lapse
Solution 1:
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?
Solution 2:
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"
Solution 3:
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.
Solution 4:
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'
Solution 5:
.NET 4 accepts format in 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()));
}