将日期从人类可读格式转换为纪元失败

Conversion of date from human-readable format to epoch fails

我想创建一个程序,将特定人类可读格式的日期转换为纪元。

到目前为止,我有以下代码,其中第一部分创建了这种人类可读的格式,第二部分将其转换为纪元。

#include <time.h>
#include <iostream>
#include <ctime>
#include <string>
#include <cstring>

using namespace std;

int main(int argc, char const *argv[])
{
     time_t timeNow;
     struct tm *ltm = NULL;
     time(&timeNow);
     ltm = localtime(&timeNow);
     char buffer[100];
     strftime(buffer, sizeof(buffer), "%c %Z", ltm);
     cout << "human readable timestamp  is " << buffer << endl;
     std::tm tmNow;
     memset(&tmNow, 0, sizeof(tmNow));
     strptime(buffer, "%c %Z", &tmNow);
     cout << "epoch timestamp  is " <<  mktime(&tmNow) << endl;
     return 0;
}

所以我得到的打印输出如下:

human readable timestamp is Thu Sep 16 10:23:06 2021 EEST
epoch timestamp  is 1631780586

我的时区是东欧夏令时,但纪元是错误的,因为它提前一小时。正确的应该是 1631776986。我想我在当地时间上做错了什么。我已经找到第三方库示例,如 boost 或 poco 进行这种转换,但我更喜欢使用本机 C++ 完成上述转换。
有人看到我遗漏了什么吗?

C timing/calendrical API 很难正确使用(这就是 C++ 逐渐远离它的原因)。

来自C standard

The value of tm_isdst is positive if Daylight Saving Time is in effect, zero if Daylight Saving Time is not in effect, and negative if the information is not available.

在调用 mktime 之前设置 tmNow.tm_isdst = -1;