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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With