The difference between the dates in years

matheus matheus at gmail.com
Sat Feb 10 20:43:04 UTC 2024


On Saturday, 10 February 2024 at 19:16:35 UTC, Alexander Zhirov 
wrote:
> ...

Maybe this will help: I think if you will divide it can't be 365, 
but 365.242199.

About your code: I having tested fully, but I found a few 
problems and I wrote (Again without further tests) as below:

import std;

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;
}

int getDiffYears2(string date) {
     auto now  = cast(Date)Clock.currTime();
     auto from = Date.fromISOExtString(date);
     auto dy = now.year-from.year;
     auto dm = (from.month-now.month);
     auto dd = (dm == 0 && from.day>now.day);
	return dy - 1 * (dm > 0 || dd);
}

void main(){
     writeln("2001-02-09 is ", getDiffYears("2001-02-09"));
     writeln("2001-02-10 is ", getDiffYears("2001-02-10"));
     writeln("2001-02-11 is ", getDiffYears("2001-02-11"));
     writeln("2001-03-01 is ", getDiffYears("2001-03-01"));
     writeln("");
     writeln("2001-02-09 is ", getDiffYears2("2001-02-09"));
     writeln("2001-02-10 is ", getDiffYears2("2001-02-10"));
     writeln("2001-02-11 is ", getDiffYears2("2001-02-11"));
     writeln("2001-03-01 is ", getDiffYears2("2001-03-01"));
}

Output:

2001-02-09 is 23
2001-02-10 is 23
2001-02-11 is 22
2001-03-01 is 21

2001-02-09 is 23
2001-02-10 is 23
2001-02-11 is 22
2001-03-01 is 22

Matheus.


More information about the Digitalmars-d-learn mailing list