Get months / years between two dates.

WebFreak001 d.forum at webfreak.org
Thu May 7 11:40:36 UTC 2020


On Wednesday, 6 May 2020 at 19:51:01 UTC, bauss wrote:
> How do you exactly do that?
>
> Like if I have two dates as std.datetime.DateTime
>
> How will I get the months or years between the two dates?
>
> I was surprised to learn that Duration does not support them 
> and only has weeks, days etc. but not months or years.
>
> I can't seem to find any standard way of doing it.
>
> Will I have to calculate that myself or? I feel like that's a 
> big thing missing if it's not there already.
>
> My use-case is simple. I need to calculate years/months since a 
> specific date has happened.

A month doesn't have a specific amount days/weeks so "what is a 
month" cannot be answered from just the duration alone. You can 
use SysTime.diffMonths or DateTime.diffMonths to calculate the 
number of months between two dates. Years are always 12 months so 
you don't have to worry there and can just divide by 12

If you also want days or weeks, you will need to calculate that 
yourself afterwards


More information about the Digitalmars-d-learn mailing list