#include <stdio.h>
void main(void)
{
time_t timep
struct tm *p
int in_time[3]
int now_time[3]
int i
printf("输入年-月-日: ")
scanf("%d-%d-%d", &in_time[0], &in_time[1], &in_time[2])
time (&timep)
p=gmtime(&timep)
now_time[0]=1900+p->tm_year
now_time[1]=1+p->tm_mon
now_time[2]=p->tm_mday
for(i=0i<3i++)
if(in_time[i]>now_time[i])
{
printf("你输入的日期大\n")
break
}
else if(in_time[i]<now_time[i])
{
printf("你输入的日期小\n")
break
}
else
continue
if(i==3)
printf("两个日期一样大\n")
// printf("%d\n",p->tm_sec) /*获取当前秒*/
// printf("%d\n",p->tm_min) /*获取当前分*/
// printf("%d\n",8+p->tm_hour)/*获取当前时,这里获取西方的时间,刚好相差八个小时*/
// printf("%d\n",p->tm_mday)/*获取当前月份日数,范围是1-31*/
// printf("%d\n",1+p->tm_mon)/*获取当前月份,范围是0-11,所以要加1*/
// printf("%d\n",1900+p->tm_year)/*获取当前年份,从1900开始,所以要加1900*/
// printf("%d\n",p->tm_yday) /*从今年1月1日算起至今的天数,范围为0-365*/
}
c语言时间函数:1、获得日历时间函数:
可以通过time()函数来获得日历时间(Calendar Time),其原型为:time_t time(time_t * timer)
如果已经声明了参数timer,可以从参数timer返回现在的日历时间,同时也可以通过返回值返回现在的日历时间,即从一个时间点(例如:1970年1月1日0时0分0秒)到现在此时的秒数。如果参数为空(NUL),函数将只通过返回值返回现在的日历时间,比如下面这个例子用来显示当前的日历时间:
2、获得日期和时间函数:
这里说的日期和时间就是平时所说的年、月、日、时、分、秒等信息。从第2节我们已经知道这些信息都保存在一个名为tm的结构体中,那么如何将一个日历时间保存为一个tm结构的对象呢?
其中可以使用的函数是gmtime()和localtime(),这两个函数的原型为:
struct tm * gmtime(const time_t *timer)
struct tm * localtime(const time_t * timer)
其中gmtime()函数是将日历时间转化为世界标准时间(即格林尼治时间),并返回一个tm结构体来保存这个时间,而localtime()函数是将日历时间转化为本地时间。比如现在用gmtime()函数获得的世界标准时间是2005年7月30日7点18分20秒,那么用localtime()函数在中国地区获得的本地时间会比世界标准时间晚8个小时,即2005年7月30日15点18分20秒。
计算两个年月日之间的天数,思路是分别算出日期的总天数然后相减。
要考虑闰年的情况,判断闰年的口诀:4年一闰,100年不闰,400年再闰。
((year % 4 == 0 &&year % 100 != 0) || year % 400 == 0)
网上找了一个(偷懒= =!),修改下如下:
#include <stdio.h>
int sum(int y,int m,int d)
{
unsigned char x[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}
int i,s=0
for(i=1i<yi++)
if(i%4==0 &&i%100!=0 || i%400==0)
s+=366//闰年
else
s+=365//平年
if(y%4==0 &&y%100!=0 || y%400==0)
x[2]=29
for(i=1i<mi++)
s+=x[i]//整月的天数
s+=d//日的天数
return s//返回总天数,相对公元1年
}
void main()
{
unsigned char y1,m1,d1,y2,m2,d2
int s1,s2
printf("输入第一个年 月 日:")
scanf("%d %d %d",&y1,&m1,&d1)
printf("输入第二个年 月 日:")
scanf("%d %d %d",&y2,&m2,&d2)
s1=sum(y1,m1,d1)
s2=sum(y2,m2,d2)
if (s1 >s2)
printf("相差天数:%ld\n",s1-s2)
else
printf("相差天数:%ld\n",s2-s1)
}
以上代码VC6编译测试通过。