Formatting dates the hard way

I was doing a bit of a code review and I spotted this in the code base.

string[] splitOptions = new string[1] { dayEarlier.Date.Year.ToString() };
string[] earlyDates = dayEarlier.Date.GetDateTimeFormats();
string[] earlySplit = earlyDates[67].Split(splitOptions,
earlySplit[0] = earlySplit[0].Replace(",", string.Empty);

Essentially the code gets the date in a specific format. However, it does it in the oddest most convoluted way I’ve ever seen.  Just to explain, here is the code again but this time I’ve added some comments:

// dayEarlier is a business object with a property called Date that returns a DateTime.
// splitOptions will contain the year in an 1-element string array.
string[] splitOptions = new string[1] { dayEarlier.Date.Year.ToString() };

// earlyDates will contain the dayEarlier Date in umpteen different formats.
string[] earlyDates = dayEarlier.Date.GetDateTimeFormats();

// earlySplit will contain the 68th (!) formatted date (out of 89 that get generated).
// Element 0 in this array will contain the bit upto the year, element 1 will contain
// the bit after the year. The year itself is discarded.
string[] earlySplit = earlyDates[67].Split(splitOptions,

// The first element (element 0) of earlySplit is then modified to remove the comma.
earlySplit[0] = earlySplit[0].Replace(",", string.Empty);

In short, what is actually being looked for is the day name, day of the month and the month. That’s it. And that, apparently, isn’t even in the 89 permutations of the date that .NET generated in the second line of code. To add to the potential problems with this, I’ve not seen any documentation that states that the permutations given by this method will stay the same.

All this code could easily be re-written simply as:

dayEarlier.Date.ToString("ddd dd MMM");

And the bonus here is that we are not generating 88 completely useless permutations, nor are we generating the permutation that is simply the closest match that we still have to futz around with. We are generating the date in exactly the format that we want. (Current culture permitting)


  1. Ross Dargan says:

    lol… scary – makes you wonder where whoever coded that copied and pasted it from… cant imagine anyone who knew the above wouldn’t know the tostring option also!!!

  2. Greg says:

    When I run this on my machine I get a completely different result. Oh well just proves that it really is a bad piece of code. 🙂

  3. Greg, I suspect the method returns different results based on the current culture. This application was using en-gb as the culture. I’m guessing you are not.

Leave a Comment

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

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

Facebook photo

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

Connecting to %s