How to format DateTime using ToString - Peter's Software House

How to format DateTime using ToString

Another WTF:

// I saw this code today and went WTF!!!!
string oldway = DateTime.Now.Year + "-" +    
DateTime.Now.Month.ToString("00") + "-" + DateTime.Now.Day.ToString("00") +    
    "T" + DateTime.Now.Hour.ToString("00") + ":" + DateTime.Now.Minute.ToString("00") +    
    ":" + DateTime.Now.Second.ToString("00");

// I changed it to this
string newWay = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");

// And to prove it worked I placed it all in a test and checked that both returns the same result.
Assert.AreEqual(oldway, newWay);
Published Friday, July 24, 2009 1:52 PM by Pieter
Filed under: ,

Comments

# re: How to format DateTime using ToString

As a further improvement you should use CultureInfo.DateTimeFormat.ShortDatePattern and CultureInfo.DateTimeFormat.ShortTimePattern if possible

Friday, July 24, 2009 6:11 AM by codingsanity

# re: How to format DateTime using ToString

One person's solution is another's WTF. To me your code is a WTF.

.NET already supports that format -- it is a variant of the ISO8601 format family. All you have to specify in the format string is "s".

DateTime.Now.ToString("s"/*yyyy-MM-ddTHH:mm:ss*/);

Monday, July 27, 2009 7:54 AM by Mark Nicholson

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: