 # How to: Calculate Number of Week and Number of Day

I am involve in a project to develop a digital clock based on arduino and a GLCD (128x64). yes, i know... one more project about clocks....

In any case, this post is to show how i solved something that i didn´t found at Time Library. I wanted to show the number of day in the year (from 1 to 365 or 366), and the number of week (1 to 53), and i share here how i solved the problem.

Here is where i saw all the necessary information: http://en.wikipedia.org/wiki/ISO_week_date

Here is the function:

``````void DayWeekNumber(unsigned int y, unsigned int m, unsigned int d, unsigned int w){
int days[]={0,31,59,90,120,151,181,212,243,273,304,334};    // Number of days at the beginning of the month in a not leap year.
//Start to calculate the number of day
if (m==1 || m==2){
DN = days[(m-1)]+d;                     //for any type of year, it calculate the number of days for January or february
}                        // Now, try to calculate for the other months
else if ((y % 4 == 0 && y % 100 != 0) ||  y % 400 == 0){  //those are the conditions to have a leap year
DN = days[(m-1)]+d+1;     // if leap year, calculate in the same way but increasing one day
}
else {                                //if not a leap year, calculate in the normal way, such as January or February
DN = days[(m-1)]+d;
}
// Now start to calculate Week number
if (w==0){
WN = (DN-7+10)/7;             //if it is sunday (time library returns 0)
}
else{
WN = (DN-w+10)/7;        // for the other days of week
}
}
``````

you need to declare two global variables:

``````short DN;   //Returns the number of day in the year
short WN;   //Returns the number of the week in the year
``````

and this is how you need to call the function in your loop:

``````  DayWeekNumber(year(),month(),day(),weekday());
``````

Take into account that i use TIME library in my sketch, so how you call to year, month, day and day of week could change for other libraries.

and this is an example of how to call the function and show the results:

``````DayWeekNumber(year(),month(),day(),weekday());
Serial.print("Day #");
Serial.print(DN);
Serial.print(" at week # ");
Serial.print(WN);
Serial.print(" of ");
Serial.println(year());
``````

Be aware than in the function, there is a problematic line:

``````    WN = (DN-7+10)/7;
``````

This is because in the library the week starts on Sunday (0), however, in the ISO standard, week start on monday (1), and sunday is the last day (7). For that reason, i included this especial case in the code.

I hope it could be useful to you. Fell free to use, improve, include in your time management libraries or RTC control libraries, or share it. Cheers,