简体   繁体   English

比较2个包含时间和日期的字符串

[英]compare 2 string containing time and date

I'm writing a C code and have a problem in comparing 2 variable containing time. 我正在编写C代码,比较2个包含时间的变量时遇到问题。 The first time are acquired from a database which is in string format. 首次从字符串格式的数据库中获取。 The second date are to get the current local time. 第二个日期是获取当前本地时间。 Since the first date is in string. 由于第一个日期是字符串。 I decide to make the second time also in string. 我决定第二次也使用字符串。 The problem is how to compare the 2 variable to see which one is bigger or earlier? 问题是如何比较2个变量以查看哪个更大或更早? At first I tried strncmp. 起初,我尝试了strncmp。 But then, that function check the size of the string. 但是然后,该函数检查字符串的大小。 I tried to change the string into number format but still failed. 我试图将字符串更改为数字格式,但仍然失败。 My idea is to use difftime, but then again, my time is in string and not time_t format. 我的想法是使用difftime,但是再说一次,我的时间是字符串形式,而不是time_t格式。 Is it possible to change from string into time_t? 是否可以从字符串更改为time_t? Can anyone suggest a function that can help me do the operation? 谁能建议一个可以帮助我进行操作的功能?

I'm following this topic as a guidance. 我正在遵循此主题作为指导。 comparing two dates with different format in C 比较两个日期不同的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;

} }

This is the output from my code. 这是我的代码的输出。

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

this is because your code ignores time values: 这是因为您的代码会忽略时间值:

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

for pure C i think you're need to use sscanf function to parse string to set of integers, like this: 对于纯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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM