Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

datetime - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...