Nov 252012
 

Converting from date to string in C# is really easy. Basic components are y M d H m s and you go from there:

var date = new DateTime(2008, 3, 1);
Console.WriteLine(date.ToString("yyyy-MM-dd")); //2008-03-01
Console.WriteLine(date.ToString("yyyy")); //2008
Console.WriteLine(date.ToString("MM")); //03
Console.WriteLine(date.ToString("dd")); //01

Of course you can also use format without leading zeros:
var date = new DateTime(2008, 3, 1);
Console.WriteLine(date.ToString("yyyy-M-d")); //2008-3-1
Console.WriteLine(date.ToString("M")); //March 1 (or something similar) - WTF?
Console.WriteLine(date.ToString("d")); //2008-11-01 (or something similar) - WTF?

Looking at first line one would expect d and M to give day and month without leading zero. In .NET these characters lead double life. For example, if d is given alone it really means standard date and time format specifier. Similar goes for M.

Solution is quite simple. If you really need to use them alone, just prepend percent character (%):

var date = new DateTime(2008, 3, 1);
Console.WriteLine(date.ToString("yyyy-M-d")); //2008-3-1
Console.WriteLine(date.ToString("%M")); //3
Console.WriteLine(date.ToString("%d")); //1

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>