Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert "2012-03-02" into unix epoch time in C?

A string "2012-03-02" representing March 2nd, 2012 is given to me as an input variable (char *).

How do I convert this date into unix epoch time in C programming language?

like image 440
user1068636 Avatar asked Mar 03 '12 00:03

user1068636


2 Answers

Local time or UTC? If it's UTC, the easiest way to do the conversion is to avoid the C time API entirely and use the formula in POSIX for seconds since the epoch:

tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
    (tm_year-70)*31536000 + ((tm_year-69)/4)*86400 -
    ((tm_year-1)/100)*86400 + ((tm_year+299)/400)*86400

Source: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_15

If it's local time, the problem turns into hell due to the fact that time_t is not guaranteed to be represented as seconds since the epoch except on POSIX systems, and the fact that it's difficult to compute a time_t value corresponding to the epoch (mktime will not work because it uses local time). Once you compute the time_t for the epoch, though, it's just a matter of using mktime for the time value you parsed and then calling difftime.

like image 186
R.. GitHub STOP HELPING ICE Avatar answered Sep 17 '22 23:09

R.. GitHub STOP HELPING ICE


Extract the pieces with an sscanf, populate struct tm (from <time.h>) with the data extracted, and finally use mktime to convert it to time_t.

time_t ParseDate(const char * str)
{
    struct tm ti={0};
    if(sscanf(str, "%d-%d-%d", &ti.tm_year, &ti.tm_mon, &ti.tm_day)!=3)
    {
        /* ... error parsing ... */
    }
    ti.tm_year-=1900
    ti.tm_mon-=1
    return mktime(&ti);
}
like image 31
Matteo Italia Avatar answered Sep 20 '22 23:09

Matteo Italia