Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimeSpan to Custom string like HH:mm:ss [duplicate]

I would like to convert

var delta = TimeSpan.FromSeconds(10);

to string like 00:00:01

I try this delta.ToString(@"0:\\hh\\:mm\\:ss", System.Globalization.CultureInfo.InvariantCulture);

But nothing is working fine. Also I cannot find here https://msdn.microsoft.com/en-us/library/ee372287.aspx correct way to do it.

Method ToString() does not help so i need in format lie hh:mm:ss.

enter image description here Any clue?

like image 214
Friend Avatar asked Jul 09 '16 19:07

Friend


People also ask

How to Convert TimeSpan to string in asp net c#?

ToString(String, IFormatProvider) Converts the value of the current TimeSpan object to its equivalent string representation by using the specified format and culture-specific formatting information.

What format is TimeSpan?

NET Framework 4. "c" is the default TimeSpan format string; the TimeSpan. ToString() method formats a time interval value by using the "c" format string. TimeSpan also supports the "t" and "T" standard format strings, which are identical in behavior to the "c" standard format string.

How do I convert DateTime to TimeSpan?

To convert a DateTime to a TimeSpan you should choose a base date/time - e.g. midnight of January 1st, 2000, and subtract it from your DateTime value (and add it when you want to convert back to DateTime ). If you simply want to convert a DateTime to a number you can use the Ticks property. Save this answer.

What is TimeSpan C#?

C# TimeSpan struct represents a time interval that is difference between two times measured in number of days, hours, minutes, and seconds. C# TimeSpan is used to compare two C# DateTime objects to find the difference between two dates.


1 Answers

Just use :

delta.ToString(); // 00:00:10

which does the trick for you (Fiddle)

Or try this:

var str = string.Format("{0:00}:{1:00}:{2:00}", delta.Hours, delta.Minutes, delta.Seconds);

You can build an extension method if you use it a lot:

public static class MyExtensions
{
    public static string ToCustomString(this TimeSpan span)
    {
        return string.Format("{0:00}:{1:00}:{2:00}", span.Hours, span.Minutes, span.Seconds);
    }
}

Usage:

string strSpan = delta.ToCustomString();
like image 188
Zein Makki Avatar answered Oct 31 '22 11:10

Zein Makki