c# - 如何将 TimeSpan 转换为格式化字符串?

标签 c# timespan

<分区>

我有两个 DateTime 变量,beginTime 和 endTime。我通过执行以下操作获得了它们的区别:

TimeSpan dateDifference = endTime.Subtract(beginTime);

我现在如何使用 C# 以 hh hrs, mm mins, ss secs 格式返回一个字符串。

如果差异是 00:06:32.4458750

它应该返回这个 00 小时 06 分 32 秒

最佳答案

我刚刚构建了几个 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} 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;
}

关于c# - 如何将 TimeSpan 转换为格式化字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/842057/

相关文章:

c# - 将秒转换为 HH :MM:SS with String. 格式

c# - 时间跨度四舍五入到小数点后 3 位

c# - 将 AM/PM 时间字符串解析为 TimeSpan

c# - IDataReader 如何定义它的索引器?

c# - 服务堆栈错误构建 View 页面

c# - 正则表达式仅匹配单词中的第一个字母

c# - Elmah 不过滤/拦截 web api 上的错误

c# - 如何模拟按下Fn+F6?

c# - 将 TimeSpan 添加到给定的 DateTime

c# - TimeSpan字符串格式异常