Board index » cppbuilder » TDatetime difference in days, months and years

TDatetime difference in days, months and years


2005-10-15 02:15:42 AM
cppbuilder70
Hi,
I have been browsing the newsgroups for a long time trying to find if
this issue has been resolved by somebody. I found some solutions, but
they are not very accurate. Sometimes they get one day less or they
don't count the number of months correctly.
I've tried everything in my code with no success.
Does anybody knows a way to do it?
Thanks a lot.
 
 

Re:TDatetime difference in days, months and years

Star wrote:
Quote
Hi,

I have been browsing the newsgroups for a long time trying to find if
this issue has been resolved by somebody. I found some solutions, but
they are not very accurate. Sometimes they get one day less or they
don't count the number of months correctly.

I've tried everything in my code with no success.

Does anybody knows a way to do it?

Thanks a lot.
Here is what I have used.
class TDateDif
{
int Years;
int Months;
int Days;
int DaysBetween;
bool GE; // True if EndDate>= StartDate.
public:
TDateDif(TDateTime StartDate,TDateTime EndDate);
~TDateDif() {}
int years() { return Years; }
int months() { return Months; }
int days() { return Days; }
int daysBetween() { return DaysBetween; }
bool ge() { return GE; }
};
TDateDif::TDateDif(TDateTime StartDate,TDateTime EndDate) :
Years(0),
Months(0),
Days(0),
DaysBetween(0),
GE(true)
{
if (StartDate == EndDate)
return;
DaysBetween = ::DaysBetween(StartDate,EndDate);
if (EndDate < StartDate)
{
GE = false;
DaysBetween = -DaysBetween;
TDateTime TmpDate = StartDate;
StartDate = EndDate;
EndDate = TmpDate;
}
unsigned short Year, Month, Day;
StartDate.DecodeDate(&Year,&Month,&Day);
TDateTime Date = IncMonth(StartDate,1);
while (Date <= EndDate)
{
Months++;
Date = IncMonth(Date,Months);
int day = Day;
while (!IsValidDate(YearOf(Date),MonthOf(Date),day))
day--;
Date = TDateTime(YearOf(Date),MonthOf(Date),day);
}
Date = StartDate;
if (Months)
Date = IncMonth(Date,Months);
Days = ::DaysBetween(Date,EndDate);
Years = Months / 12;
Months %= 12;
if (!GE)
{
Days = -Days;
Months = -Months;
Years = -Years;
}
} // TDateDif::TDateDif
HTH,
Danzer
 

Re:TDatetime difference in days, months and years

Danzer wrote:
...
Thanks, Danzer!! I will give it a try.
 

{smallsort}

Re:TDatetime difference in days, months and years

Star wrote:
Quote
Danzer wrote:
...

Thanks, Danzer!! I will give it a try.
If you find an error please post or email your results.
 

Re:TDatetime difference in days, months and years

Star < XXXX@XXXXX.COM >wrote:
Quote
TDatetime difference in days, months and years
I found some solutions, but they are not very accurate.
Just a remark: month itself is not accurate - can be anything
from 28 to 31 days. So don't look for accuracy, but for a
solution that fits best your concrete context/problem.