On Saturday, 10 February 2024 at 18:12:07 UTC, Alexander Zhirov wrote:
On Saturday, 10 February 2024 at 16:03:32 UTC, H. S. Teoh wrote:
On Sat, Feb 10, 2024 at 03:53:09PM +0000, Alexander Zhirov via Digitalmars-d-learn 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.

IIRC you can just subtract two DateTime's to get a Duration that you can then convert into whatever units you want. Only thing is, in this case conversion to months may not work because months don't have a fixed duration (they can vary from 28 days to 31 days) so there is no "correct" way of computing it, you need to program it yourself according to the exact calculation you want.


T

I did it this way, but there will be an inaccuracy, since somewhere there may be 366 days, and somewhere 365

```
auto d = cast(Date)Clock.currTime() - Date.fromISOExtString("2001-02-01");
writeln(d.total!"days"().to!int / 365);
```

```
int getDiffYears(string date) {
    auto currentDate = cast(Date)Clock.currTime();
    auto startDate = Date.fromISOExtString(date);
    auto currentDay = currentDate.dayOfYear;
    auto startDay = startDate.dayOfYear;
    auto currentMonth = currentDate.month;
    auto startMonth = startDate.month;
    auto diffDays = currentDate - startDate;
    auto diffYears = diffDays.total!"days"().to!int / 365;

return currentMonth >= startMonth && currentDay >= startDay ? diffYears : diffYears - 1;
}
```

Reply via email to