Convert string from __DATE__ into a time_t

后端 未结 7 995
小蘑菇
小蘑菇 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条回答
  •  天涯浪人
    2021-02-07 18:33

    Here is how I modified your sample to use with mbed for Arm32 micro controllers in C++.

    // Convert compile time to system time 
    time_t cvt_date(char const *date, char const *time)
    {
        char s_month[5];
        int year;
        struct tm t;
        static const char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
        sscanf(date, "%s %d %d", s_month, &t.tm_mday, &year);
        sscanf(time, "%2d %*c %2d %*c %2d", &t.tm_hour, &t.tm_min, &t.tm_sec);
        // Find where is s_month in month_names. Deduce month value.
        t.tm_mon = (strstr(month_names, s_month) - month_names) / 3 + 1;    
        t.tm_year = year - 1900;    
        return mktime(&t);
    }
    

    See: https://developer.mbed.org/users/joeata2wh/code/compile_time_to_system_time/ for complete code. Also see https://developer.mbed.org/users/joeata2wh/code/xj-Init-clock-to-compile-time-if-not-alr/ for an example of how I use it to initialize a clock chip based on the compile time.

提交回复
热议问题