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

How to get UTC offset from string

本文关键字:获取 UTC 偏移量 字符串      更新时间:2023-10-16

我得到字符串像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