【问题标题】:compare 2 string containing time and date比较包含时间和日期的 2 个字符串
【发布时间】: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

【问题讨论】:

标签: c string time


【解决方案1】:

这是因为您的代码忽略了时间值:

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

【讨论】:

    猜你喜欢
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    • 2023-03-28
    • 2012-12-20
    • 1970-01-01
    • 2014-05-25
    相关资源
    最近更新 更多