简体   繁体   中英

How do I calculate months between two dates in C

I have a scenario where the monthly charges are calculated by the system over a span of 18 months. Say for example, the charges are 10$ ; the will then calculate $10/18 = $0.56 monthly.

If the customer cancels the service in the middle of the 18months period. I need to find the number of months he has used and refund the rest. Ex: Customer created on Jun 2,2012 and cancel on Aug 13,2012, which means he used for 2 month completely and hence I need to refund ($10/18)* (18-2) .

Since this is only going to be needed over a range of a few years - I would build a lookup table manually of the time_t value for the start of each month.

Then record the time_t they started the service, check the time_t now and then scan the table for the number of values between these.

ps. time_t is the 'C' stdlib basis for time functions, it's the number of seconds since 1970 and is used by all the functions in time.h

If I understand correctly, you want to calculate amount of full months between two dates... So algorithm can be like this:

curDate  = fromDate;
curDate.month++;
totMonths = 0;
while (curDate < fromDate) {
    totMonths++;
    if (curDate.month == 12) {
        curDate.month = 1;
        curDate.year++;
    } else curDate.month++;
}

You can create a method which will calculate this, however a better way of doing it is, writing an ADT to represent a date object which should do all the calculation on its own

int chargeFor(int createdD,int createdM,int createdY,int canceledD,int canceledM,int canceledY){
   int deltaD = canceledD - createdD;
   int deltaM = canceledM - createdM;
   int deltaY = canceledD - createdD;

   if( deltaD != 0 )
      return result = deltaY * 12 + deltaM + 1; 
   else 
      return result = deltaY * 12 + deltaM; 

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM