The difference between the dates in years
Steven Schveighoffer
schveiguy at gmail.com
Sun Feb 11 02:45:37 UTC 2024
On Saturday, 10 February 2024 at 15:53:09 UTC, Alexander Zhirov
wrote:
> Is it possible to calculate the difference between dates in
> years using regular means? Something like that
>
>
> ```
> writeln(Date(1999, 3, 1).diffMonths(Date(1999, 1, 1)));
> ```
>
> At the same time, keep in mind that the month and day matter,
> because the difference between the year, taking into account
> the month that has not come, will be less.
>
> My abilities are not yet enough to figure it out more elegantly.
OK, so I thought this was already taking into account the day of
the month.
This is what I came up with:
```d
int diffMonthNew(Date d1, Date d2)
{
auto diff = d1.diffMonths(d2);
if(diff > 0)
return diff + (d1.day < d2.day ? -1 : 0);
else if(diff < 0)
return diff + (d1.day > d2.day ? 1 : 0);
return 0;
}
```
Then if you want the years, it would be `diffMonthNew(d1, d2) /
12`
-Steve
More information about the Digitalmars-d-learn
mailing list