1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
| #include <string.h>
#include <stdlib.h>
#include <stdio.h>
/* l'année est-elle bissextile*/
int Bissextile (int A)
{
return A % 4 == 0 && (A % 100 != 0 || A % 400 == 0);
}
/*combien de jours se sont ecoules depuis le debut de l'annee donnee*/
int Nb_Jours (int J, int M, int A)
{
int i, D = 0;
const int Mois[12]= {31,28,31,30,31,30,31,31,30,31,30,31};
if (M == 1)
{
D = J;
}
else
{
for (i = 0; i < (M-1); i++)
{
D += Mois[i];
}
D+=J;
}
if ((M > 2) && (Bissextile(A)))
{
D++;
}
return D;
}
/*la fonction diff proprement dite*/
int Diff (int j1, int m1, int a1, int j2, int m2, int a2)
{
int NJ = 0, NJ1, NJ2, i;
NJ1 = Nb_Jours (j1, m1, a1);
NJ2 = Nb_Jours (j2, m2, a2);
if (a2 == a1)
{
NJ = NJ2 - NJ1;
}
else
{
for (i = 0; i < (a2-a1); i++)
{
NJ += 364;
if (Bissextile (a1+i))
{
NJ++;
}
}
NJ -= NJ1;
NJ += NJ2+1;
}
return NJ;
}
/* fonction substring pour extraire les sous chaines */
char* substring(const char* str, size_t begin, size_t len)
{
if (str == 0 || strlen(str) == 0 || strlen(str) < begin || strlen(str) < (begin+len))
return 0;
return strndup(str + begin, len);
}
/****************************************************************/
/* Fonction diff_dates_en_jours : clacule le nombre de jours */
/* qui sépare deux dates, en tenant compte des années bissextiles */
/****************************************************************/
int diff_dates_en_jours(char date_debut_contrat[8+1],char date_fin_contrat[8+1])
{
const char* date1 = date_debut_contrat;
char* annee1 = substring(date1, 0, 4);
char* mois1 = substring(date1, 4, 2);
char* jour1 = substring(date1, 6, 2);
const char* date2 = date_fin_contrat;
char* annee2 = substring(date2, 0, 4);
char* mois2 = substring(date2, 4, 2);
char* jour2 = substring(date2, 6, 2);
int nombre_jours= Diff (atoi(jour1), atoi(mois1), atoi(annee1),atoi(jour2), atoi(mois2), atoi(annee2));
free(annee1);
free(mois1);
free(jour1);
free(annee2);
free(mois2);
free(jour2);
return nombre_jours;
}
/****************************************************************/
/* appel diff_dates_en_jours*/
/****************************************************************/
int main (void)
{
int calcul=0;
calcul=diff_dates_en_jours ("20100105","20100127");
printf("calcul = %d ! \n", calcul);
return 0;
} |
Partager