首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C++计算2个带时区的字符串的时间差

C++计算2个带时区的字符串的时间差
EN

Stack Overflow用户
提问于 2021-02-17 16:50:50
回答 1查看 227关注 0票数 0

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

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

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

代码语言:javascript
运行
复制
    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));

代码给出了2次之间的1秒差。但它没有考虑时区的差异。

如何在考虑时区的情况下获得差值(在本例中,差值为2小时零1秒

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

编辑:

为了获取当前日期,我使用了以下命令:

代码语言:javascript
运行
复制
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;
}
EN

回答 1

Stack Overflow用户

发布于 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

代码语言:javascript
运行
复制
#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值。然后你就可以减去它们了。

此程序输出:

代码语言:javascript
运行
复制
-7201s

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

  • #include "date/date.h"
  • using namespace date;
  • using date::operator<<;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66238566

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档