Convert seconds to days , hh:mm:ss C#
Asked Answered
E

3

10

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.

Emptor answered 18/6, 2015 at 5:45 Comment(2)
u can add ur desire character in toString Method with "\" before ur character ==> t.ToString(@"d\d\,hh\:mm\:ss")Quadrangle
can you give an example? Are you meaning this return t.ToString(@"%., hh:mm:ss") ?Emptor
C
8

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.

Ciborium answered 18/6, 2015 at 5:51 Comment(0)
F
1

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");
Flaggy answered 18/6, 2015 at 5:54 Comment(0)
P
0
return t.ToString(@"d\d\, hh\:mm\:ss")
Pieper answered 18/6, 2015 at 6:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.