The difference between the dates in years

Alexander Zhirov azhirov1991 at gmail.com
Sat Feb 10 18:12:07 UTC 2024


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);
```


More information about the Digitalmars-d-learn mailing list