c++ - 如何从字符串中获取 UTC 偏移量

标签 c++

我得到类似 2015-04-29 15:36:16.5761891 +03:00 的字符串。我可以使用 std::get_time 轻松提取日期。

std::tm time;
std::string stringTime = "2015-04-29 15:36:16.5761891 +03:00";
std::istringstream stringStream(stringTime);
stringStream >> std::get_time(&time, "%Y-%m-%d %H:%M:%S");

cout << time.tm_year << endl;
cout << time.tm_mon << endl;
cout << time.tm_mday << endl;
cout << time.tm_hour << endl;
cout << time.tm_min << endl;
cout << time.tm_sec << endl;

它对我来说很好用。现在如何从此字符串中提取 UTC 偏移量?

最佳答案

你可以这样继续阅读:

#include <ctime>
#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>

int main()
{
    std::tm time;
    std::string stringTime = "2015-04-29 15:36:16.5761891 +03:00";

    std::istringstream stringStream(stringTime);

    std::string decimals;
    std::string offset;
    stringStream >> std::get_time(&time, "%Y-%m-%d %H:%M:%S") >> decimals >> offset;

    std::cout << time.tm_year << '\n';
    std::cout << time.tm_mon << '\n';
    std::cout << time.tm_mday << '\n';
    std::cout << time.tm_hour << '\n';
    std::cout << time.tm_min << '\n';
    std::cout << time.tm_sec << '\n';

    std::cout << decimals << '\n';
    std::cout << offset << '\n';
}

输出:

115
3
29
15
36
16
.5761891
+03:00

关于c++ - 如何从字符串中获取 UTC 偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30577762/

相关文章:

c++ - 指针互换性与具有相同地址

C++如何创建一个自动转换图?

c++ - 如何构建解析树?

c++ - 检查二维数组中相邻方 block 的值

c++ - 从 friend 类继承时无法使用大括号括起来的初始值设定项列表

c++ - 自定义 header 高于标准?

c++ - 寻求帮助解决 c++ 八皇后难题代码

c++ - CreateThread 的参数不正确

c++ - CRTP子类和实例列表

c++ - 从套接字读取一个字节与多个字节