Take control of DateTime’s ToString() method.
Posted by Vadim on June 19, 2008
Today I had to write to the database a string that satisfies following format: DDMMYYYY-CountryCode. For example if DateTime object equal to 06/19/2008 and country code is USA, the value written to the database must be “06192008-USA“.
The best way I found to do that is to use ToString() method of DateTime object with custom date and time format.
someDate.ToString("MMddyyy-") + CountryCode;
NOTE: In the format above I used two ‘M’s and two ‘d’s. If only one ‘M’ and one ‘d’ was used, no month or date would be padded with zero.
someDate.ToString("Mdyyy-") + CountryCode;
The output for the code above would be “6192008-USA” assuming that the date is 06/19/2008 and the country code is USA.
UPDATE: I had to change the lines of code above because it had a bug. Thanks to Alexey Romanov for pointing it out. I put one line of code for the world to see and it was buggy.
The previous code looked like this:
someDate.ToString(String.Format("MMddyyy-{0}"), CountryCode);
Let assume that CountryCode is MEX. In this case it’s the same as:
someDate.ToString("MMddyyy-MEX");
Remember that “M” is a special character for DateTime object. The output for this code would be “06192008-6EX“. It definitely is a problem.



Alexey Romanov said
What happens if the country code happens to include a meaningful (for DateTime.ToString) character?
Vadim said
Alexey, it’s a good point. We should refactor code like this:
someDate.ToString(“MMddyyy-") + CountryCode;John S. said
Add single quotes: someDate.ToString(String.Format(“MMddyyy-’{0}’”), CountryCode);
See: http://john-sheehan.com/blog/wp-content/uploads/msnet-formatting-strings.pdf
Vadim said
John,
Thanks for the tip. Single quotes definitely works. You have very nice cheat sheets. Thanks for sharing.