gpt4 book ai didi

c - 如何使用 difftime() 比较日期?

转载 作者:行者123 更新时间:2023-11-30 16:39:06 26 4
gpt4 key购买 nike

#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;
}

在执行中查看它 here

关于c - 如何使用 difftime() 比较日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47205348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com