I am converting a series of date/value pairs from one DB into another that uses offset/value pairs. The offsets are defined as the number of years, months and days since the first date. .Net appears to lack any simple way to calculate these values. I found this solution on MS's pages (and of course, can't find it now). P is a date/value pair:
Dim span As TimeSpan = P.StartDate - FirstStartDate
Dim testdate As DateTime = Date.MinValue + span
years = testdate.Year - 1 ' because MinValue is year 1
months = testdate.Month - 1
days = testdate.Day - 1
The idea is that you create a date by adding the TimeSpan to another date - in this case MinValue, and then ask the resulting date for it's year/month/day. So for instance, if the span is a year, the resulting date will be 0002/1/1 and then the result of the calculations will be 1/0/0.
So here's the problem: let's say you have a series of dates like this:
2019/1/1
2020/1/1
2023/1/1
2026/1/1
What happens is that the third entry is four years after the start date, so it calculates that this is in year 0004. And year 0004 is a leap year. But 2023 is not. So the calculation of the span from the start date includes a leap year that should not be there and it is off by one day.
There are dozens of threads about this sort of calculation here on SO, but looking over the answers they all have caveats where they don't work in one place or another, and leap years are a common cause of issues. Before I just start hacking this, is there a canonical solution to this problem that does not require importing the VisualBasic (or other) library?