C++ Converting a time string to seconds from the e

2019-01-14 13:27发布

I have a string with the following format:

2010-11-04T23:23:01Z

The Z indicates that the time is UTC.
I would rather store this as a epoch time to make comparison easy.

What is the recomended method for doing this?

Currently (after a quck search) the simplist algorithm is:

1: <Convert string to struct_tm: by manually parsing string>
2: Use mktime() to convert struct_tm to epoch time.

// Problem here is that mktime uses local time not UTC time.

10条回答
\"骚年 ilove
2楼-- · 2019-01-14 13:57

You can use a function such as strptime to convert a string to a struct tm, instead of parsing it manually.

查看更多
够拽才男人
3楼-- · 2019-01-14 14:01

What's wrong with strptime() ?

And on Linux, you even get the 'seconds east of UTC' field relieving you from any need to parse:

#define _XOPEN_SOURCE
#include <iostream>
#include <time.h>

int main(void) {

    const char *timestr = "2010-11-04T23:23:01Z";

    struct tm t;
    strptime(timestr, "%Y-%m-%dT%H:%M:%SZ", &t);

    char buf[128];
    strftime(buf, sizeof(buf), "%d %b %Y %H:%M:%S", &t);

    std::cout << timestr << " -> " << buf << std::endl;

    std::cout << "Seconds east of UTC " << t.tm_gmtoff << std::endl;
}   

which for me yields

/tmp$ g++ -o my my.cpp 
/tmp$ ./my
2010-11-04T23:23:01Z -> 04 Nov 2010 23:23:01
Seconds east of UTC 140085769590024
查看更多
迷人小祖宗
4楼-- · 2019-01-14 14:02

This is ISO8601 format. You can use strptime function to parse it with %FT%T%z argument. It is not a part of the C++ Standard though you can use open source implementation of it (this, for instance).

查看更多
来,给爷笑一个
5楼-- · 2019-01-14 14:08

Using C++11 functionality we can now use streams to parse times:

The iomanip std::get_time will convert a string based on a set of format parameters and convert them into a struct tz object.

You can then use std::mktime() to convert this into an epoch value.

#include <iostream>
#include <sstream>
#include <locale>
#include <iomanip>

int main()
{
    std::tm t = {};
    std::istringstream ss("2010-11-04T23:23:01Z");

    if (ss >> std::get_time(&t, "%Y-%m-%dT%H:%M:%S"))
    {
        std::cout << std::put_time(&t, "%c") << "\n"
                  << std::mktime(&t) << "\n";
    }
    else
    {
        std::cout << "Parse failed\n";
    }
}
查看更多
登录 后发表回答