如何在c中将datetime转换为unix时间戳?

liu*_*liu 20 c unix datetime timestamp

场景是:我使用libexif以"YYYY-MM-DD HH:MM:SS"格式获取日期时间.为了最大限度地降低节省成本,我想将日期时间转换为unix时间戳或类似,仅花费64位或32位.c有什么明确的方法吗?

Kje*_*sen 32

您可以尝试strptimemktime的组合

struct tm tm;
time_t epoch;
if ( strptime(timestamp, "%Y-%m-%d %H:%M:%S", &tm) != NULL )
  epoch = mktime(&tm);
else
  // badness
Run Code Online (Sandbox Code Playgroud)

  • 我知道一定有类似strptime的东西,但是我找不到。我有99%的时间使用Microsoft,但他们不支持。 (3认同)
  • 作为旁注,如果您使用的是Windows,请参阅此问题:http://stackoverflow.com/questions/321849/strptime-equivalent-on-windows (3认同)
  • 我建议使用 `timegm()` 而不是 `mktime()` 以避免时区问题。 (2认同)

Mar*_*som 5

将日期/时间的每个部分转换为整数以填充a struct tm,然后将其转换为time_t使用mktime.