Khaustov Kirill
Khaustov Kirill

Reputation: 69

How to get UTC offset from string

I'm getting string like 2015-04-29 15:36:16.5761891 +03:00. I can easily exctract the date using 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;

It's working fine for me. Now how can I extract UTC offset from this string?

Upvotes: 4

Views: 682

Answers (1)

Galik
Galik

Reputation: 48605

You can just keep on reading like this:

#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';
}

Output:

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

Upvotes: 2

Related Questions