The difference between the dates in years
Lance Bachmeier
no at spam.net
Sat Feb 10 21:56:30 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.
I'm assuming you mean you want the number of full years between
the dates. If so, I use something like this:
```
import std;
void main() {
writeln(fullYears(Date(1999, 3, 1), Date(1999, 2, 1)));
writeln(fullYears(Date(2000, 3, 1), Date(1999, 2, 1)));
writeln(fullYears(Date(2000, 3, 1), Date(1999, 4, 1)));
writeln(fullYears(Date(2006, 4, 1), Date(1999, 4, 1)));
}
bool earlierInYear(Date date1, Date date2) {
return date1 < Date(date1.year, date2.month, date2.day);
}
long fullYears(Date date1, Date date2) {
assert(date1 >= date2, "The first date has to be later");
if (date1.earlierInYear(date2)) {
return max(date1.year - date2.year, 0);
} else {
return date1.year - date2.year;
}
}
```
More information about the Digitalmars-d-learn
mailing list