Questa serie di funzioni dovrebbe esserti utile:
codice:typedef struct tagData { short Giorno; short Mese; short Anno; } Data; /*Restituisce 1 se l'anno è bisestile, 0 altrimenti*/ int IsAnnoBisestile(short nAnno) { if ( nAnno % 4 != 0 ) { return 0; } else { if ( nAnno % 100 != 0 ) return 1; else if ( nAnno % 400 != 0 ) return 0; else return 1; } } int GiorniNelMese(short nMese, short nAnno) { switch ( nMese ) { case 2: if ( IsAnnoBisestile(nAnno) ) return 29; else return 28; case 4: case 6: case 9: case 11: return 30; default: return 31; } } /* Somma nGiorni alla data dt e restituisce la data corrispondente*/ Data SommaGiorni(Data dt, unsigned int nGiorni) { Data dtRet; dtRet.Giorno = dt.Giorno; dtRet.Mese = dt.Mese; dtRet.Anno = dt.Anno; for ( int i = 0; i < nGiorni; i++ ) { if ( dtRet.Giorno < GiorniNelMese(dtRet.Mese, dtRet.Anno) ) { dtRet.Giorno++; } else { dtRet.Giorno = 1; if ( dtRet.Mese != 12 ) { dtRet.Mese++; } else { dtRet.Mese = 1; dtRet.Anno++; } } } return dtRet; } /* Sottrae nGiorni alla data dt e restituisce la data corrisponente*/ Data SottraiGiorni(Data dt, unsigned int nGiorni) { Data dtRet; dtRet.Giorno = dt.Giorno; dtRet.Mese = dt.Mese; dtRet.Anno = dt.Anno; for ( int i = 0; i < nGiorni; i++ ) { if ( dtRet.Giorno > 1 ) { dtRet.Giorno--; } else { if ( dtRet.Mese > 1 ) { dtRet.Mese--; dtRet.Giorno = GiorniNelMese(dtRet.Mese, dtRet.Anno); } else { dtRet.Giorno = 31; dtRet.Mese = 12; dtRet.Anno--; } } } return dtRet; } /* ConfrontaDate restituisce: zero se le due date sono uguali; un valore maggiore di zero se dt1 > dt2; un valore minore di zero se dt1 < dt2. */ int ConfrontaDate(Data dt1, Data dt2) { if ( dt1.Anno == dt2.Anno && dt1.Mese == dt2.Mese && dt1.Giorno == dt2.Giorno ) return 0; else if (dt1.Anno == dt2.Anno ? dt1.Mese == dt2.Mese ? dt1.Giorno > dt2.Giorno : dt1.Mese > dt2.Mese : dt1.Anno > dt2.Anno) return 1; else return -1; } /* Calcola la differenza in giorni tra due date */ int Differenza(Data dt1, Data dt2) { int nRet = 0; Data d1; Data d2; if ( ConfrontaDate(dt1, dt2) == 0 ) return 0; else if ( ConfrontaDate(dt1, dt2) > 0 ) { d1 = dt2; d2 = dt1; } else { d1 = dt1; d2 = dt2; } do { nRet++; d1 = SommaGiorni(d1, 1); } while ( ConfrontaDate(d1, d2) != 0 ); return nRet; }

Rispondi quotando