C + + writes a small program that calculates the number of days between two dates:
[CPP]View PlainCopy
- #include <Windows.h>
- #include <stdio.h>
- struct tagdate
- {
- int year;
- int month;
- int day;
- };
- Set Date
- void SetDate (int y, int m, int D, tagdate *date)
- {
- Date->year = y;
- Date->month = m;
- Date->day = D;
- }
- Whether a leap year
- int isleapyear (int year)
- {
- return ((year%4==0) && (year%100!=0) | | year%400==0);
- }
- Maximum number of days to get Date.month
- int Getlastday (tagdate date)
- {
- int num;
- switch (date.month)
- {
- Case 1:
- Case 3:
- Case 5:
- Case 7:
- Case 8:
- Case Ten:
- Case :
- num=31;
- Break ;
- Case 2:
- num = 28+isleapyear (date.year);
- Break ;
- Default:
- num = 30;
- }
- return num;
- }
- Date is legal
- int Isdatevalid (tagdate date)
- {
- if (date.year <0 | | date.month <1 | | date.month>)
- return 0;
- if (date.day <1 | | date.day> getlastday (date))
- return 0;
- return 1;
- }
- Date+1
- void Addday (Tagdate *date)
- {
- date->day++;
- if (Date->day > Getlastday (*date))
- {
- Date->day = 1;
- date->month++;
- if (Date->month >)
- {
- Date->month = 1;
- date->year++;
- }
- }
- }
- Date1 than Date2 small return value is 1, otherwise 0
- int Compare (tagdate date1, Tagdate date2)
- {
- if (Date1.year < date2.year)
- return 1;
- if (date1.year <= date2.year && date1.month < Date2.month)
- return 1;
- if (date1.year <= date2.year && date1.month <= date2.month && date1.day < Date2.day)
- return 1;
- return 0;
- }
- Calculate the number of days between two dates
- Long DateDiff (Tagdate date1, Tagdate date2)
- {
- long delta = 0;
- Tagdate Date3;
- //If date1 > Date2, Exchange Date1,date2
- if (! Compare (Date1, date2))
- {
- Date3 = Date2;
- Date2 = Date1;
- Date1 = Date3;
- }
- //date1 than Date2, date1 date plus 1
- While (Compare (date1,date2))
- {
- Addday (&DATE1);
- delta++;
- }
- return delta;
- }
- void Main ()
- {
- Tagdate Date1, Date2;
- int y, M, D;
- System ("CLS");
- While (1)
- {
- Puts ("\ninput date1\t");
- scanf ("%d,%d,%d", &y, &m, &d);
- SetDate (Y, M, D, &date1);
- if (! Isdatevalid (date1))
- {
- Puts ( "Date1 is invalid!");
- Exit (1);
- }
- Puts ("\ninput date2\t");
- scanf ("%d,%d,%d", &y, &m, &d);
- SetDate (Y, M, D, &date2);
- if (! Isdatevalid (date2))
- {
- Puts ( "Date2 is invalid!");
- Exit (1);
- }
- //
- printf ("\nresult: [%ld]", DateDiff (Date1,date2));
- }
- }
52194332
C + + calculates the number of days between any two dates