[英]How do i compare dates using difftime()?
#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()的函數,但是由於我是新手,所以我不知道該怎么做。 任何幫助表示贊賞,謝謝。
您可以執行以下操作:
#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;
}
在這里查看執行情況
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.