#include <stdio.h>
#include <time.h>
int date_txt[5],today_date;
scanf("%d",&today_date); //i enter (input) the date manually e.g. 20171109
date_txt[0]=20161102; // year month day form (rrrrmmdd)
date_txt[1]=20150101;
date_txt[2]=20170615;
date_txt[3]=20160628;
date_txt[4]=20150101;
我有几个日期需要与today_date进行比较,看看差异是否等于或大于1年。我发现存在一个叫做difftime()的函数,但由于我是新手,我不知道如何做到这一点。感谢任何帮助,谢谢。
答案 0 :(得分:0)
您可以这样做:
#include <stdio.h>
#include <time.h>
#define COUNT 5
#define SECONDS_NON_LEAP_YEAR (365*24*3600)
#define SECONDS_LEAP_YEAR (366*24*3600)
typedef struct tm T_TIME;
T_TIME dToday, dTemp;
void convertToTime(int iDate, T_TIME* tTime)
{
tTime->tm_mday = iDate%100;
iDate/=100;
tTime->tm_mon = (iDate%100)-1;
iDate/=100;
tTime->tm_year = iDate-1900;
}
int isLeapYear(int yyyy)
{
if(yyyy%100) // Not a century
{
return !(yyyy%4);
}
return !(yyyy%400);
}
int main(void) {
int date_txt[]={20161102, 20150101, 20170615, 20160628, 20150101};
int today_date, i, flg, isThisYearLeap, tSeconds;
scanf("%d",&today_date); //i enter (input) the date manually e.g. 20171109 year month day form (rrrrmmdd)
convertToTime(today_date, &dToday);
isThisYearLeap = isLeapYear(dToday.tm_year+1900);
for(i=0;i<COUNT; i++)
{
convertToTime(date_txt[i], &dTemp);
tSeconds = difftime(mktime(&dToday), mktime(&dTemp));
flg = (isThisYearLeap || isLeapYear(dTemp.tm_year+1900)) ?
(tSeconds >= SECONDS_LEAP_YEAR) : (tSeconds >= SECONDS_NON_LEAP_YEAR);
printf("The difference between Today and date %d is %s 1 year.\n", date_txt[i],
(flg ? "Greater than or equals to" : "Less than"));
}
return 0;
}
在执行here
中查看