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

前端 未结 10 562
無奈伤痛
無奈伤痛 2020-12-01 14:53

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 t

相关标签:
10条回答
  • 2020-12-01 15:19

    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";
        }
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-01 15:19

    You could utilize the boost::date_time and write a small manual parser (probably regexp-based) for your strings.

    0 讨论(0)
  • 2020-12-01 15:20

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

    0 讨论(0)
  • 2020-12-01 15:27

    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
    
    0 讨论(0)
提交回复
热议问题