繁体   English   中英

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

[英]compare 2 string containing time and date

我正在编写C代码,比较2个包含时间的变量时遇到问题。 首次从字符串格式的数据库中获取。 第二个日期是获取当前本地时间。 由于第一个日期是字符串。 我决定第二次也使用字符串。 问题是如何比较2个变量以查看哪个更大或更早? 起初,我尝试了strncmp。 但是然后,该函数检查字符串的大小。 我试图将字符串更改为数字格式,但仍然失败。 我的想法是使用difftime,但是再说一次,我的时间是字符串形式,而不是time_t格式。 是否可以从字符串更改为time_t? 谁能建议一个可以帮助我进行操作的功能?

我正在遵循此主题作为指导。 比较两个日期不同的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;
}

暂无
暂无

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

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