将秒数转换为天数,hh:mm:ss C#

Convert seconds to days , hh:mm:ss C#

我需要将秒转换为 3d, 02:05:45 格式。使用以下函数,我可以将其转换为 3.02:05:45。我不确定如何将其转换为我想要的格式。请帮忙。

private string ConvertSecondsToDate(string seconds)
{
    TimeSpan t = TimeSpan.FromSeconds(Convert.ToDouble(seconds));

    if (t.Days > 0)
        return t.ToString(@"d\.hh\:mm\:ss");
    return t.ToString(@"hh\:mm\:ss");

}

如果我尝试做这样的事情 return t.ToString(@"%d , hh\:mm\:ss") 我收到一个错误,

input string is not in correct format.

如果我没理解错的话,可以espace d 字符加白space 跟\ 一样;

if (t.Days > 0)
    return t.ToString(@"d\d\,\ hh\:mm\:ss");

if (t.Days > 0)
    return t.ToString(@"d'd, 'hh\:mm\:ss");

结果将被格式化为 3d, 02:05:45

来自Other Characters section in Custom TimeSpan Format Strings

Any other unescaped character in a format string, including a white-space character, is interpreted as a custom format specifier. In most cases, the presence of any other unescaped character results in a FormatException.

There are two ways to include a literal character in a format string:

  • Enclose it in single quotation marks (the literal string delimiter).

  • Precede it with a backslash ("\"), which is interpreted as an escape character. This means that, in C#, the format string must either be @-quoted, or the literal character must be preceded by an additional backslash.

https://msdn.microsoft.com/en-us/library/ee372287.aspx

Any [other] unescaped character in a format string, including a white-space character, is interpreted as a custom format specifier. In most cases, the presence of any other unescaped character results in a FormatException. There are two ways to include a literal character in a format string:

  • Enclose it in single quotation marks (the literal string delimiter).
  • Precede it with a backslash ("\"), which is interpreted as an escape character. This means that, in C#, the format string must either be @-quoted, or the literal character must be preceded by an additional backslash.
private string ConvertSecondsToDate(string seconds)
{
     TimeSpan t = TimeSpan.FromSeconds(Convert.ToDouble(seconds));

     if (t.Days > 0)
         return t.ToString(@"d\d\,\ hh\:mm\:ss");
     return t.ToString(@"hh\:mm\:ss");
}

或者

 if (t.Days > 0)
     return t.ToString(@"d'd, 'hh':'mm':'ss");
return t.ToString(@"d\d\, hh\:mm\:ss")