Write a c program to calculate difference between two dates.

แนะนำ สอบถาม ภาษา C สำหรับผู้เริ่มต้น

Moderator:

User avatar
nokroo
Posts: 188
Joined: 01/01/1970 7:00 am
Location: วัดตะคร้ำเอน ต.ตะคร้ำเอน อ.ท่ามะกา จ.กาญจนบุรี

Write a c program to calculate difference between two dates.

Postby nokroo » 05/10/2013 9:05 am

#include<stdio.h>
#include<conio.h>
#include<time.h>
time_t time(time_t *t);
main()
{
int y2,m2,d2,y,m,d;
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("Time now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
y2=tm.tm_year+1900;
m2=tm.tm_mon+1;
d2=tm.tm_mday;
printf("Enter the Reference Date in DD MM YY format\n");
scanf("%d%d%d",&d,&m,&y);
int loop,total_days = 0,days_in_a_year;
int day,month,year;
int month_days[] = {31,28,31,30,31,30,31,31,30,31,30,31};
printf("\n%d\n%d\n%d\n",(y2-y),(m2-m),(d2-d));
printf("%d",month_days[m]);
if(((y2-y)==0&&(m2-m)<1&&(d2<d))||(y2<y)||(m<1)||(m>12)||(d<0)||(d>month_days[m-1]))
{
printf("\nInvalid Reference Date\n");
}
else
{
total_days=month_days[m-1]-d;
if((m==2)&&((y%4)==0))
total_days+=1;
for(int i=m;i<12;i++)
{
if((y%4==0)&&i==1)
total_days+=1;
total_days+=month_days[i];
}
for(int year=y+1;year<y2;year++)
{
if(year%4==0)
total_days+=366;
else
total_days+=365;
}
for(int i=0;i<m2-1;i++)
{
if((y2%4==0)&&i==1)
total_days+=1;
total_days+=month_days[i];
}
total_days+=d2;
if((y2==y)&&(y%4==0))
total_days-=366;
if((y2==y)&&(y%4!=0))
total_days-=365;
}
printf("\nThe date difference is %d\n",total_days);
getch();
}

Image

Return to “Programming - C/C<sup>++</sup>& java”

Who is online

Users browsing this forum: No registered users and 2 guests