Hello,
I'm trying to perfect the date calculation code of my clock. While the clock has no problem when I increase the days (i.e. they eventually fall back to 1 and months are increased by 1), I get into troubles when I decrease them : sometimes it works correctly (i.e. days fall back to 31 or 31 or 28 or 29, depending on the month), but sometimes days get negative, even if I included a statement preventing this. It's really weird.
Here is the code. Everything is in the loop. The "days", "ClockMonthSet" and "ClockYearSet" are set with inputs earlier in the code. The relevant (and non-working) variables are "Jour", "Mois", and "Annee" :
// DATE CALCULATION /////////////////////////////////
// (non-working with decreasing days) ///////////////
int Jour = days; //We define new variables to play with without affecting what's above.
int Mois = ClockMonthSet;
int Annee = ClockYearSet;
//Number of days in a month:
byte February;
if(Annee%4==0) February=29;
else February=28;
byte MonthArray[13] = {0,31,February,31,30,31,30,31,31,30,31,30,31}; //we'll skip the first entry, so we can use the array's index directly.
//Defining Month incrementation.
for(byte i=1;i<13;i++){
if(Mois==i){
if(Jour>MonthArray[i]){ //If "Jour" exceeds the number of days in the present month, it is resetted to 1 and we step into the next month.
Jour -= MonthArray[i];
Mois++;
}
if(Jour<1){ //Similarly if "Jour" is to become 0.
if(i-1==0) i=13; //Before January comes December.
Jour += MonthArray[i-1];
Mois--;
}
}
}
//Defining years incrementation.
if(Mois>12){
Annee++;
Mois-=12;
}
if(Mois<1){
Annee--;
Mois+=12;
}
The "for" statement at the beginning might seem odd, but this is the solution I found to fix my previous code, which had a bigger problem : the "if" statement seemed to be checked only once. For the first month, things worked nice, but for the second month and after, days would increase with no limits, regardless of my "if" :
// DATE CALCULATION /////////////////////////////////
// (not working at all past the first month) ////////
int Jour = days; //We define new variables to play with without affecting what's above.
int Mois = ClockMonthSet;
int Annee = ClockYearSet;
//Number of days in a month:
byte February;
if(Annee%4==0) February=29;
else February=28;
byte MonthArray[13] = {0,31,February,31,30,31,30,31,31,30,31,30,31}; //we'll skip the first entry, so we can use the array's index directly.
//Defining Month incrementation.
if(Jour>MonthArray[Mois]){ //If "Jour" exceeds the number of days in the present month, it is resetted to 1 and we step into the next month.
Jour -= MonthArray[Mois];
Mois++;
}
if(Jour<1){ //Similarly if "Jour" is to become 0.
Jour += MonthArray[Mois-1];
Mois--;
}
//Defining years incrementation.
if(Mois>12){
Annee++;
Mois-=12;
}
if(Mois<1){
Annee--;
Mois+=12;
}
This is by no means urgent, as the clock keeps the date correct day after day (with the first code), but i'd like my code to work not only "apparently".
Any help appreciated.