# Compute the calender days given 2 dates

Discussion in 'C' started by srikanth_cforum, Dec 21, 2010.

1. ### srikanth_cforumNew Member

Joined:
Dec 21, 2010
Messages:
1
0
Trophy Points:
0
Dear friends,
I am implementing a requirement on a microcontroller having a real time clock. When the controller is powered up, i capture the starting time to a static variable say begin = 20/12/2010 (ofcourse i will have 3 variables for month date and year.

I want to calculate on demand, the number of days elapsed since power on.
Since i am using a microcontroller, i do not have the flexibility of using the standard libraries (epoch time for example in linux).

Can some one help me with this ? may be a code snippet or somestarting point would be great

Cheers!

2. ### imported_viswanathanNew Member

Joined:
Dec 22, 2010
Messages:
2
0
Trophy Points:
0
Hi,
i am giving the seudo code for it, Let me know if you face any further problem..

Regards,
Viswanathan.R
9865650093
rviswawt@gmail.com

Code:
```#include<stdio.h>
int main(void)
{
/* Store month information */
int month[]={31,28,31,30,31,30,31,31,30,31,30,31};

/* Get the current date and time OFF */
int cu_date,cu_month,cu_year;

/* Get the previous date and time ON */
int pre_date,pre_month,pre_year;

/* Local Variable */
int i,elap_days = 0; /* inital ellapsed days

/* Get the date when it is powered on */
printf("\n Enter the starting date \n When the Micro is powered on\n");
scanf("%d/%d/%d",&pre_date,&pre_mont,&pre_year);

/* Get the date when it powered off */
printf("\n Enter the current date\n");
scanf("%d/%d/%d",&cu_date,&cu_mont,&cu_year);

/* Calculate  the number of days between the starting nad ending year */
for(i= cur_year+1;i<pre_year-1;i++)
{
if((cur_year+1)%4==0)
{
elap_days=elaps_days+366; /* Leap year*/
}
else
elap_days=elaps_days+365;
}

if(cu_year==pre_year)
{
if(cu_month<=2) /* Iw was switched ON in Jan or FEB
{
if(cu_year%4 == 0)
month[1]=29;
}
for(i=cu_month+1;i<((cu_year==pre_year)? cu_month-1:12);i++)
{
elap_days= month[i]+elap_days;
}
if(cu_month == pre_month) /* if power on and OFF fall on the same month */
{
elap_days = cu_days-pre_day;
}
else
{
elap_days = (month[pre_month]-pre_day)+cu_day + elap_day;
}
}

/* switch ON and OFF are falling in different years */
if(cu_year!=pre_year)
{
if(pre_month=>2)
{
if(pre_year%4 == 0)
month[1]=29;

}
for(i=0;i< cu_month-1;i++)
{
elap_days= month[i]+elap_days;
}
elap_days = elap_days+cur_days;

}
print the elap_days
return 0;

}```