Timespan格式
这个问题在这里已经有了答案:
没有内置功能,您需要使用自定义方法,如下所示:
TimeSpan ts = new TimeSpan(0, 70, 0);
String.Format("{0} hour{1} {2} minute{3}",
ts.Hours,
ts.Hours == 1 ? "" : "s",
ts.Minutes,
ts.Minutes == 1 ? "" : "s")
public static string Pluralize(int n, string unit)
{
if (string.IsNullOrEmpty(unit)) return string.Empty;
n = Math.Abs(n); // -1 should be singular, too
return unit + (n == 1 ? string.Empty : "s");
}
public static string TimeSpanInWords(TimeSpan aTimeSpan)
{
List<string> timeStrings = new List<string>();
int[] timeParts = new[] { aTimeSpan.Days, aTimeSpan.Hours, aTimeSpan.Minutes, aTimeSpan.Seconds };
string[] timeUnits = new[] { "day", "hour", "minute", "second" };
for (int i = 0; i < timeParts.Length; i++)
{
if (timeParts[i] > 0)
{
timeStrings.Add(string.Format("{0} {1}", timeParts[i], Pluralize(timeParts[i], timeUnits[i])));
}
}
return timeStrings.Count != 0 ? string.Join(", ", timeStrings.ToArray()) : "0 seconds";
}
从这里复制我自己的答案:如何将TimeSpan转换为格式化的字符串?
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} days, ", span.Days) : string.Empty,
span.Duration().Hours > 0 ? string.Format("{0:0} hours, ", span.Hours) : string.Empty,
span.Duration().Minutes > 0 ? string.Format("{0:0} minutes, ", span.Minutes) : string.Empty,
span.Duration().Seconds > 0 ? string.Format("{0:0} seconds", span.Seconds) : string.Empty);
if (formatted.EndsWith(", ")) formatted = formatted.Substring(0, formatted.Length - 2);
if (string.IsNullOrEmpty(formatted)) formatted = "0 seconds";
return formatted;
}
链接地址: http://www.djcxy.com/p/18499.html
上一篇: Timespan formatting