Convert string from __DATE__ into a time_t

后端 未结 7 987
小蘑菇
小蘑菇 2021-02-07 18:25

I\'m trying to convert the string produced from the __DATE__ macro into a time_t. I don\'t need a full-blown date/time parser, something that only han

7条回答
  •  -上瘾入骨i
    2021-02-07 18:39

    Edit: the corrected function should look something like this:

    time_t cvt_TIME(char const *time) { 
        char s_month[5];
        int month, day, year;
        struct tm t = {0};
        static const char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
    
        sscanf(time, "%s %d %d", s_month, &day, &year);
    
        month = (strstr(month_names, s_month)-month_names)/3;
    
        t.tm_mon = month;
        t.tm_mday = day;
        t.tm_year = year - 1900;
        t.tm_isdst = -1;
    
        return mktime(&t);
    }
    

提交回复
热议问题