#include <stdio.h>
#include <time.h>
#include<math.h>
#define TRUE 1
#define FALSE 0
size_t StringToDatetime(char *str)
{
time_t ocurtime;
char buffer[80];
struct tm tm_;
int year, month, day;
sscanf(str,"%d-%d-%d", &year, &month, &day);
tm_.tm_year = year-1900;//occur time
tm_.tm_mon = month-1;
tm_.tm_mday = day;
tm_.tm_hour = 0;
tm_.tm_min = 0;
tm_.tm_sec = 0;
tm_.tm_isdst = 0;
time_t curtime;//current time
curtime = time(NULL);
ocurtime=mktime(&tm_);
if( ocurtime == -1 )
{
printf("错误:不能使用 mktime 转换时间。\n");
return FALSE;
}
else
{
return floor(difftime(curtime,ocurtime)/(3600*24)); //秒时间
}
}
int main(){
char str[]="2020-9-08"
/*当前时间字串,理论上可以提供更多参数,参数格式需参照sscanf内格式化输入的传参格式,但小时,分钟和秒对天数之差没有影响;
*/
time_t Diff=StringToDatetime(str);
printf("the gap day frorm %s to current day is :%ld",str,Diff);
return 0;
}
运行之后:
2020-9-08距离今天2020/9/29相差21天,结论正确。
参考材料:https://blog.csdn.net/charliye/article/details/50720812