Tuesday, April 22, 2008

Formatting DateTime Strings

The DateTime object has some handy built in methods to format your date like .ToShortDateString() or .ToLongTimeString(). But often you need to combine two formats. Here are some ideas.
string format1 = string.Format("{0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString());
Here, I am just concatenating the output from two methods. There must be an easier way! To get the same exact output, you can customize the format of your ToString() output:
string format2 = DateTime.Now.ToString("M/dd/yyyy h:mm:ss tt");
You could also encapsulate this functionality into an extension method if you use it enough:
public static class DateTimeExtensions
{
    public static string ToShortDateLongTimeString(this DateTime d)
    {
        return d.ToString("M/dd/yyyy h:mm:ss tt");
    }
}
// ...
// To consume this extension method:
string format3 = DateTime.Now.ToShortDateLongTimeString();

More Info: MSDN: DateTime.ToString
More Info: List of ToString Formats