esp8266 – How to parse 20180810T143000Z to time_t

0
39

Parsing the string really is the only way. However there are many ways of doing it.

My preferred method is to first check that the format is correct, by looking for the T and Z being in the right place:

if (timeString[8] == 'T' && timeString[15] == 'Z') {
    ... parse in here
}

And the parsing is just making numbers with multiplication:

int year = (timeString[0] - '0') * 1000 +
           (timeString[1] - '0') * 100 +
           (timeString[2] - '0') * 10 +
           (timeString[3] - '0');

You can clean things up with a macro if you like:

#define NUM(off, mult) ((timeString[(off)] - '0') * (mult))

Then:

int year =   NUM(0, 1000) + NUM(1, 100) + NUM(2, 10) + NUM(3, 1);
int month =  NUM(4, 10)   + NUM(5, 1);
int day =    NUM(6, 10)   + NUM(7, 1);
int hour =   NUM(9, 10)   + NUM(10, 1);
int minute = NUM(11, 10)  + NUM(12, 1);
int second = NUM(13, 10)  + NUM(14, 1);

And then, yes, put them in a struct tm (or directly assign them calculation results without using the intermediate variables) and call mktime().

LEAVE A REPLY

Please enter your comment!
Please enter your name here