【发布时间】:2013-12-09 17:29:58
【问题描述】:
我正在编写 C 代码,但在比较 2 个包含时间的变量时遇到问题。第一次是从字符串格式的数据库中获取的。第二个日期是获取当前本地时间。由于第一个日期是字符串。我决定第二次也用字符串。问题是如何比较 2 变量来查看哪个更大或更早?起初我尝试了strncmp。但是,该函数会检查字符串的大小。我试图将字符串更改为数字格式,但仍然失败。我的想法是使用 difftime,但话又说回来,我的时间是字符串而不是 time_t 格式。是否可以从字符串更改为 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
【问题讨论】:
-
检查
strptime()函数可以将字符串转换为struct tm。 -
这将对您有所帮助。 stackoverflow.com/questions/15555406/…