A cautionary tale, always be careful with your DateTime manipulations (or how I showed the Internet I was an idiot)

A couple of silly mistakes I made while working with `DateTime` object manipulations. Its a short read and hopefully you will remember my folly the next time you need to tweak your dates.

I wrote some code last month (November) which worked great for me. Patting myself on back I shipped the code:

DateTime today = DateTime.Today;
DateTime startOfNextMonth = new DateTime(today.Year, today.Month + 1, 1);

Can you see straight away what the problem is? It’s December now, month 12 and apparently `today.Month + 1` when `.Month == 12` doesn’t wrap around.

Welcome to the exception zone because you just tried to create a thirteenth month.

I bet there is some built in code that handles this for me right? A quick perusal of IntelliSense and yes, there is an `.AddMonths()` method which will handle this for me.

A new snippet is produced and the exception goes away:

DateTime today = DateTime.Today;
DateTime startOfNextMonth = DateTime(today.Year, today.AddMonths(1).Month, 1);

What a clever chap, I’ve wrapped the month round cleanly and all is well with the world.

I was just about to move on then I noticed that a sum column wasn’t showing anywhere near the correct value. It didn’t take a breakpoint for me to realise; I’d just swapped one bug for another.

My new code wasn’t making the first of the next month, it was taking me back to January for the current year.

Tweaking the code to add the month onto the year as well so that it wraps the year nicely and I have finally managed to write a line of fit-for-purpose code:

DateTime today = DateTime.Today;
DateTime startOfNextMonth = DateTime(today.AddMonths(1).Year, today.AddMonths(1).Month, 1);

Third time lucky hey! I guess this is why people do TDD…

No comments :