Magic strings for converting DateTime to string Using C#
<p>I was greeted with a nasty bug today. The task is pretty trivial, all I needed to do is to convert the DateTime object to string in <strong><em>"yyyymmdd"</em></strong> format. The "yyyymmdd" part was stated in the development doc from the external software vendor. So, I conveniently copied the string from their file and pasted to my code. So I got the next</p>

<pre><code>public string GetDateString(DateTime dateTime)
{
    return dateTime.ToString("yyyymmdd");
}
</code></pre>

<p>Pretty simple. So simple that I didn't feel like to unit test the method. 20 minutes later, when other parts of my component are done. I started the app to check if things went right. Almost immediately I notice some supposed-to-be date field in my web page is displaying <strong>20091511</strong>! This can't be right, there is no 15th month of a year. So, I rushed back to my code to check possible errors. It turns out the that I should have used "yyyyMMdd" instead of "yyyymmdd" when converting DateTime to string. </p>

<p>Admitted, this bug was due to my lack of attention to details. The difference between "mm" and "MM" are cleared stated in all C# references. I still would like to argue that it's pretty easy to overlook the differences if one doesn't work with this kind of tasks everyday. </p>

<p>My question is: Is there a clean(i.e. no magic string) way to do the coverings in one line of code? The<code>return dateTime.Year + "" + dateTime.Month + "" + dateTime.Day;</code> code seems to be working but it's too much like hacking. </p>

<p>Update: Looks like the string format way is the best C# can offer. Maybe I am being brain washed, but I still think this kind of programming style belongs to low-level languages such as c.  </p>
