Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

timespan

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.

like image 294
RMu Avatar asked Jun 18 '15 05:06

RMu


1 Answers

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.

like image 90
Soner Gönül Avatar answered Oct 23 '22 19:10

Soner Gönül