How can I String.Format a TimeSpan object with a custom format in .NET?
Please note: this answer is for .Net 4.0 and above. If you want to format a TimeSpan in .Net 3.5 or below please see JohannesH's answer.
Custom TimeSpan format strings were introduced in .Net 4.0. You can find a full reference of available format specifiers at the MSDN Custom TimeSpan Format Strings page.
Here's an example timespan format string:
string.Format("{0:hh\\:mm\\:ss}", myTimeSpan); //example output 15:36:15
(UPDATE) and here is an example using C# 6 string interpolation:
$"{myTimeSpan:hh\\:mm\\:ss}"; //example output 15:36:15
You need to escape the ":" character with a "\" (which itself must be escaped unless you're using a verbatim string).
This excerpt from the MSDN Custom TimeSpan Format Strings page explains about escaping the ":" and "." characters in a format string:
The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd.hh:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.
How do I convert a TimeSpan to a formatted string?
Would TimeSpan.ToString() do the trick for you? If not, it looks like the code sample on that page describes how to do custom formatting of a TimeSpan
object.
How to format TimeSpan to string before .NET 4.0
One way could be:
TimeSpan ts = DateTime.Now - DateTime.Now.AddHours(-10);
Console.WriteLine(string.Format("{0:00}:{1:00}:{2:00}", ts.TotalHours, ts.Minutes, ts.Seconds));
Result would be something like:
09:59:59
EDIT:
Or you can try:
TimeSpan ts = DateTime.Now - DateTime.Now.AddHours(-10);
DateTime mydate = new DateTime(ts.Ticks);
Console.WriteLine(mydate.ToString(("hh:mm:ss")));
Output would be:
09:59:59
TimeSpan to Custom string like HH:mm:ss
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();
Custom string formats of TimeSpan
TimeSpan has no formatting options at all before .NET 4.0, you'd have to convert it to DateTime through the Ticks property. Nothing remotely close in DateTime.String(format) formatting options though, you'll have to write it yourself.
In .NET 4.0, TimeSpan acquired a ToString(format) override. Custom formatting strings are described here. Your 3rd requirement is going to need code.
C# + Format TimeSpan
Try this:
Console.WriteLine("{0:D2}:{1:D2}", duration.Minutes, duration.Seconds);
TimeSpan ToString [d.]hh:mm
I take it you're trying to do something like the optional day and fractional seconds portions of the c
standard format. As far as I can tell, this isn't directly possible with custom format strings. TimeSpan FormatString with optional hours is the same sort of question you have, and I'd suggest something similar to their solution: have an extension method build the format string for you.
public static string ToMyFormat(this TimeSpan ts)
{
string format = ts.Days >= 1 ? "d'.'hh':'mm" : "hh':'mm";
return ts.ToString(format);
}
Then to use it:
var myString = ts.ToMyFormat();
Related Topics
Problem With Converting Int to String in Linq to Entities
How to Evaluate a C# Expression Dynamically
How to Divide Two Integers to Get a Double
Calculate Md5 Checksum For a File
Selenium C# Webdriver: Wait Until Element Is Present
How to Remove Duplicates from a C# Array
Pass Array Parameter in Sqlcommand
Hresult: 0X800A03Ec on Worksheet.Range
Is It Better to Return Null or Empty Collection
What Is the Purpose of a Question Mark After a Value Type (For Example: Int? Myvariable)
How to Spawn a Process and Capture Its Stdout in .Net
Should I Avoid 'Async Void' Event Handlers
Transparent Control Over Picturebox
What's the Strangest Corner Case You'Ve Seen in C# or .Net
Httpclient.Getasync(...) Never Returns When Using Await/Async