.Net, C#, Coding, DateTime

Take control of DateTime’s ToString() method.

DateTime_ToString 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:


Remember that “M” is a special character for DateTime object.  The output for this code would be “06192008-6EX“.  It definitely is a problem.


4 thoughts on “Take control of DateTime’s ToString() method.

  1. Alexey, it’s a good point. We should refactor code like this:

    someDate.ToString(“MMddyyy-") + CountryCode;

  2. John,
    Thanks for the tip. Single quotes definitely works. You have very nice cheat sheets. Thanks for sharing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s