SQL Server vs .NET DateTime Leap Year Arithmetic

I recently refactored some code that was performing date arithmetic in SQL Server. The code was attempting to retrieve the "same day next year" by adding 365 days to the date provided. I was refactoring this logic out of SQL Server and in to .NET, and I was concerned that .NET's DateTime arithmetic wouldn't match SQL Server. I was pleasantly surprised that the results were the same. However, I should call out that perhaps in your situation adding 365 days to a given date is not appropriate for getting the "same day next year" value. I also compared this logic when preforming a "Add years + 1" and the results were also the same. (However, to be clear, adding 365 days differed from adding 1 year, but both SQL and .NET preformed the same given the method used.)

source code: https://gist.github.com/aaronhoffman/3d997390dab7f69e6597

results table:

MethodValueStartDate.NET ResultSQL Result
AddDays3652/27/20112/27/20122/27/2012
AddYears12/27/20112/27/20122/27/2012
AddDays3652/28/20112/28/20122/28/2012
AddYears12/28/20112/28/20122/28/2012
AddDays3653/1/20112/29/20122/29/2012
AddYears13/1/20113/1/20123/1/2012
AddDays-3652/27/20122/27/20112/27/2011
AddYears-12/27/20122/27/20112/27/2011
AddDays3652/27/20122/26/20132/26/2013
AddYears12/27/20122/27/20132/27/2013
AddDays-3652/28/20122/28/20112/28/2011
AddYears-12/28/20122/28/20112/28/2011
AddDays3652/28/20122/27/20132/27/2013
AddYears12/28/20122/28/20132/28/2013
AddDays-3652/29/20123/1/20113/1/2011
AddYears-12/29/20122/28/20112/28/2011
AddDays3652/29/20122/28/20132/28/2013
AddYears12/29/20122/28/20132/28/2013
AddDays-3653/1/20123/2/20113/2/2011
AddYears-13/1/20123/1/20113/1/2011
AddDays3653/1/20123/1/20133/1/2013
AddYears13/1/20123/1/20133/1/2013
AddDays-3652/27/20132/28/20122/28/2012
AddYears-12/27/20132/27/20122/27/2012
AddDays-3652/28/20132/29/20122/29/2012
AddYears-12/28/20132/28/20122/28/2012
AddDays-3653/1/20133/1/20123/1/2012
AddYears-13/1/20133/1/20123/1/2012


Hope this helps,
Aaron


Comments

Popular posts from this blog

Search iPhone Text Messages with SQLite SQL Query

How to Turn Off Microsoft Arc Touch Mouse Scroll Sound Vibration

Configure SonarAnalyzer.CSharp with .editorconfig, no need for SonarCloud or SonarQube