how to convert datetime to unix timestamp in c?
Solution 1:
You could try a combination of strptime and mktime
struct tm tm;
time_t epoch;
if ( strptime(timestamp, "%Y-%m-%d %H:%M:%S", &tm) != NULL )
epoch = mktime(&tm);
else
// badness
Solution 2:
Convert each part of the date/time into an integer to populate a struct tm
, then convert that into a time_t
using mktime.
Solution 3:
Here is a wired solution in c/pseudo code I just hacked together. Good luck!
char * runner = NULL;
char *string_orig = "YYYY-MM-DD HH:MM:SS";
time_t time = 0;
struct tm tmp;
use strstr(string_orig, "-") and atoi foreach
tmp->tm_year ..
tmp->tm_mon ..
tmp->tm_mday ..
tmp->tm_hour ..
tmp->tm_min ..
tmp->tm_sec ..
with *runner as help
time = mktime(&tm)
Solution 4:
What about sscanf?
struct tm tmVar;
char *strVar = "YYYY-MM-DD HH:MM:SS";
time_t timeVar;
if(sscanf(strVar, "%d-%d-%d %d:%d:%d", &tm.tm_year, /* the other fields */)==6)
timeVar = mktime(&tmVar);
else
// bad format