Vadim's Weblog

Never stop learning.

Take control of DateTime’s ToString() method.

Posted by Vadim on June 19, 2008

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:

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.

About these ads

4 Responses to “Take control of DateTime’s ToString() method.”

  1. Alexey Romanov said

    What happens if the country code happens to include a meaningful (for DateTime.ToString) character?

  2. Vadim said

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

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

  3. 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

  4. Vadim said

    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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: