Convert string from __DATE__ into a time_t

后端 未结 7 681
后悔当初
后悔当初 2021-02-07 18:10

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:51

    Bruno's response was very useful for my Arduino Project. Here is a version with both __DATE__ and __TIME__

    #include <Time.h>
    #include <stdio.h>
    
    time_t cvt_date(char const *date, char const *time)
    {
        char s_month[5];
        int year;
        tmElements_t t;
        static const char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
    
        sscanf(date, "%s %hhd %d", s_month, &t.Day, &year);
        sscanf(time, "%2hhd %*c %2hhd %*c %2hhd", &t.Hour, &t.Minute, &t.Second);
    
        // Find where is s_month in month_names. Deduce month value.
        t.Month = (strstr(month_names, s_month) - month_names) / 3 + 1;
    
        // year can be given as '2010' or '10'. It is converted to years since 1970
        if (year > 99) t.Year = year - 1970;
        else t.Year = year + 30;
    
        return makeTime(t);
    }
    
    void setup()
    {
        Serial.begin(115200); 
        while (!Serial);
    
        // Show raw system strings
        Serial.println(String("__DATE__ = ") + __DATE__);
        Serial.println(String("__TIME__ = ") + __TIME__);
    
        // set system time = compile time
        setTime(cvt_date(__DATE__, __TIME__));
    
        // Show actual time
        Serial.println(String("System date = ") + month() + "/" + day() + "/" + year() + " " + hour() + ":" + minute() + ":" + second() + "\n");
    }
    
    void loop() {}
    
    0 讨论(0)
提交回复
热议问题