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

10.2k views Asked by At

I need to convert seconds in the format 3d, 02:05:45. With the below function I could convert it to 3.02:05:45. I'm not sure how to convert it to the format I wanted. Please help.

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");

}

If I try to do something like this return t.ToString(@"%d , hh\:mm\:ss") I'm getting an error,

input string is not in correct format.

3

There are 3 answers

0
Soner Gönül On BEST ANSWER

If I understand correctly, you can espace d character and additional white space with \ like;

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

or

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

Result will be formatted as 3d, 02:05:45

From 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.

0
hazzik On

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");
}

Or

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