我正在编写 C 代码,并且在比较 2 个包含时间的变量时遇到问题。第一次是从字符串格式的数据库中获取的。第二个日期是获取当前本地时间。由于第一个日期是字符串。我决定第二次也用绳子做。问题是如何比较2个变量,看看哪个更大或更早?起初我尝试了strncmp。但是,该函数会检查字符串的大小。我尝试将字符串更改为数字格式,但仍然失败。我的想法是使用 difftime,但话又说回来,我的时间是字符串而不是 time_t 格式。是否可以从 string 更改为 time_t ?谁能建议一个可以帮助我执行操作的函数?
我遵循此主题作为指导。 comparing two dates with different format in C
int seq_day(char *date) {
int y = strtol(date, &date, 10);
int m = strtol(++date, &date, 10);
int d = strtol(++date, &date, 10);
return (y*12+m)*31+d;
}
int expired_demotion_time()
{
char current_datetime[50] = {0};
int result1,result2;
get_today_str(current_datetime, sizeof(current_datetime), "%Y-%m-%dT%H:%M:%S");
printf("%s \n",current_datetime);
printf("%s \n",selected_g->database_time);
result1 = seq_day(current_datetime);
result2 = seq_day(selected_g->database_time);
printf("%d \n",result1);
printf("%d \n",result2);
if((result1==result2)||(result1>result2))
{
return 1;
}
return 0;
}
这是我的代码的输出。
2013-11-25T13:11:17 \\current date. I'm making this string to follow the exact way as the first string.
2013-11-25T13:17:43 \\demotion time. Please take note that I cannot change this since this is taken from database.
749202 \\somehow both of them produce the same number
749202
最佳答案
这是因为您的代码忽略了时间值:
int seq_day(char *date) {
int y = strtol(date, &date, 10);
int m = strtol(++date, &date, 10);
int d = strtol(++date, &date, 10);
return (y*12+m)*31+d;
}
对于纯 C,我认为你需要使用 sscanf 函数将字符串解析为整数集,如下所示:
long seq_day(char *date) {
int y,m,d,hh,mm,ss;
sscanf("%d-%d-%dT%d:%d:%d",&y,&m,&d,&hh,&mm,&ss);
return ((((y*12L+m)*31L+d)*24L+hh)*60L+mm)*60L+ss;
}
关于比较 2 个包含时间和日期的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20185449/