我需要在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", ¤tTime);
strptime(old.c_str(), "%Y-%m-%d %H:%M:%S %Z", &reqTime);
double seconds = difftime(mktime(¤tTime), mktime(&reqTime));代码给出了2次之间的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;
}发布于 2021-02-17 22:44:52
这在C++20中很容易做到,不幸的是C++20的这部分还没有发布。但是,存在一个可以与C++11/14/17一起使用的free, open-source, header-only preview of this part of C++20。
#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被定义为精确到秒的协调世界时时间戳。当使用%z分析此类型时,将偏移量应用于分析的本地时间,以获得UTC值。然后你就可以减去它们了。
此程序输出:
-7201s要将此程序移植到C++20,请删除:
#include "date/date.h"using namespace date;using date::operator<<;https://stackoverflow.com/questions/66238566
复制相似问题