Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert an ISO 8601 string to time_t in C++?

Tags:

c++

time

iso

time-t

Does anyone know how to go from an ISO-8601-formatted date/time string to a time_t? I am using C++ and it needs to work on Windows and Mac.

I have written the code but I am sure there is a version that is more "standard."

I will get a date like 2011-03-21 20:25 and I have to tell if the time is in the past or the future.

like image 810
reza Avatar asked Mar 21 '11 20:03

reza


1 Answers

One ugly hack I thought would be fun: since you only want to determine which date/time is bigger, you can convert the date to string and compare strings. ;-) (The upside is you do not need strptime which is not available everywhere.)

#include <string.h>
#include <time.h>

int main(int argc, char *argv[])
{
    const char *str = "2011-03-21 20:25";
    char nowbuf[100];
    time_t now = time(0);
    struct tm *nowtm;
    nowtm = localtime(&now);
    strftime(nowbuf, sizeof(nowbuf), "%Y-%m-%d %H:%M", nowtm);
    if (strncmp(str, nowbuf, strlen(str)) >= 0) puts("future"); else puts("past");
    return 0;
}
like image 177
Mormegil Avatar answered Oct 08 '22 11:10

Mormegil