How do I convert "2012-03-02" into unix epoch time in C?
Solution 1
C (POSIX) provides a function for this. Use strptime()
to convert the string into a struct tm
value. You can then convert the struct tm
into time_t
using mktime()
.
Solution 2
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
.
Solution 3
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);
}
user1068636
Updated on June 12, 2022Comments
-
user1068636 almost 2 years
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?
-
Matteo Italia about 12 yearsThat's not standard, C, it's POSIX.
-
rnrneverdies almost 5 years
tm_year
is current year - 1900. -
Sopalajo de Arrierez over 4 yearsWhat about doing
results=results-tm_gmtoff
to readjust by using the time zone offset? I think it is not a completely standard C (rather a extension), but I have tested it right now and it seems to be working OK. -
R.. GitHub STOP HELPING ICE over 4 years@SopalajodeArrierez: If you have tm_gmtoff you almost surely have a POSIX superset and then you have better more portable solutions via POSIX.
-
Gow. almost 3 yearsIs there any other formula/source where instead of tm_yday, I can use tm_mon and tm_mday?
-
R.. GitHub STOP HELPING ICE almost 3 years@Gow: Yes, it requires some arithmetic with number of days in each month though. Perhaps open it as a new question if you want details, referencing this question.
-
Gow. almost 3 years
-
Gow. over 2 yearsCan you tell why we need to subtract 1900 and 1 from tm_year and tm_mon ?
-
Matteo Italia over 2 yearsBecause in
struct tm
years start with 1900, and the month is 0-based. You find all the relevant information about this in the documentation.