How do I convert a TimeSpan to a formatted string? [duplicate]
I have two DateTime vars, beginTime and endTime. I have gotten the difference of them by doing the following:
TimeSpan dateDifference = endTime.Subtract(beginTime);
How can I now return a string of this in hh hrs, mm mins, ss secs format using C#.
If the difference was 00:06:32.4458750
It should return this 00 hrs, 06 mins, 32 secs
I just built a few TimeSpan Extension methods. Thought I could share:
public static string ToReadableAgeString(this TimeSpan span)
{
return string.Format("{0:0}", span.Days / 365.25);
}
public static string ToReadableString(this TimeSpan span)
{
string formatted = string.Format("{0}{1}{2}{3}",
span.Duration().Days > 0 ? string.Format("{0:0} day{1}, ", span.Days, span.Days == 1 ? string.Empty : "s") : string.Empty,
span.Duration().Hours > 0 ? string.Format("{0:0} hour{1}, ", span.Hours, span.Hours == 1 ? string.Empty : "s") : string.Empty,
span.Duration().Minutes > 0 ? string.Format("{0:0} minute{1}, ", span.Minutes, span.Minutes == 1 ? string.Empty : "s") : string.Empty,
span.Duration().Seconds > 0 ? string.Format("{0:0} second{1}", span.Seconds, span.Seconds == 1 ? string.Empty : "s") : string.Empty);
if (formatted.EndsWith(", ")) formatted = formatted.Substring(0, formatted.Length - 2);
if (string.IsNullOrEmpty(formatted)) formatted = "0 seconds";
return formatted;
}
By converting it to a datetime, you can get localized formats:
new DateTime(timeSpan.Ticks).ToString("HH:mm");
This is the shortest solution.
timeSpan.ToString(@"hh\:mm");