Favor DateTime.Add over new DateTime

February 29, 2012

By

Hooray, it’s that magical day that only comes every four years! And guess what, a bunch of date-dependent code just broke because someone didn’t account for this special day.

In a project that I’m working on, there’s some validation code that goes like this:

var thirteenYearsAgo = new DateTime(DateTime.Now.Year - 13, DateTime.Now.Month, DateTime.Now.Day);

This code is used to validate birthdate and whether we have to treat the user as a child. You should already see the problem: 13 years ago, there was no 2/29. Instead, you should favor the following (which is also much simpler to read):

var thirteenYearsAgo = DateTime.Today.AddYears(-13);
Software Engineer
Geoffrey Lehr

In addition to programming, this multitalented (and handsomely modest!) developer enjoys playing & composing music, reading SF and playing video games.

Leave a Comment