c++用时区计算两个字符串之间的时间差



我需要检查c++中两个字符串时间戳之间的差异。时间戳中包含时区(%Z)变量。

我使用diff time函数来获得差值

简而言之,这就是我尝试过的代码:

string current = "2021-02-17 11:26:55 +04";
string old = "2021-02-17 11:26:56 +02";
cout<<current<<endl;
cout<<old<<endl;

struct tm currentTime, reqTime;
strptime(current.c_str(), "%Y-%m-%d %H:%M:%S %Z", &currentTime);
strptime(old.c_str(), "%Y-%m-%d %H:%M:%S %Z", &reqTime);
double seconds = difftime(mktime(&currentTime), mktime(&reqTime));

代码给出两个时间之间的1秒差。但是它没有考虑时区的差异。

考虑到时区(在这个例子中,差异是2小时1秒),我如何得到差异?

或者我如何手动将时间转换为GMT,然后进行差异

编辑:

使用以下命令获取当前日期:

string currentDateTime() {
time_t     now = time(0);
struct tm  tstruct;
char       buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S %Z", &tstruct);
return buf;
}

这在c++ 20中很容易做到。不幸的是,c++ 20的这一部分还没有发布。然而,有一个免费的、开源的、只提供头文件的c++ 20的预览版,可以在c++ 11/14/17中使用。

#include "date/date.h"
#include <chrono>
#include <iostream>
#include <sstream>
std::chrono::seconds
diff(std::string const& current, std::string const& old)
{
using namespace std;
using namespace std::chrono;
using namespace date;
istringstream in{current + " " + old};
in.exceptions(ios::failbit);
sys_seconds tp_c, tp_o;
in >> parse("%F %T %z", tp_c) >> parse(" %F %T %z", tp_o);
return tp_c - tp_o;
}
int
main()
{
using date::operator<<;
std::cout << diff("2021-02-17 11:26:55 +04",
"2021-02-17 11:26:56 +02") << 'n';
}

上面,sys_seconds被定义为秒精度的UTC时间戳。当使用%z对该类型进行解析时,将偏移量应用于解析后的本地时间,以获得UTC值。然后你可以把它们相减。

程序输出:

-7201s

要将此程序移植到c++ 20,删除:

  • #include "date/date.h"
  • using namespace date;
  • using date::operator<<;

最新更新