How to convert "2012-03-02" to the unix era in C?

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

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

+5
source share
4 answers

C (POSIX) provides a function for this. Use strptime()to convert a string to a value struct tm. Then you can convert struct tmto time_twith mktime().

+2
source

Extract the fragments with sscanf, fill in the struct tmfrom with the <time.h>extracted data and finally use mktimeto 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);
}
+2

UTC? UTC, - C- API POSIX :

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

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

, - , time_t , POSIX, , time_t (mktime , ). , time_t , mktime , , difftime.

+1

Read it in struct tmand call mktimeto receive time_t.

0
source

All Articles