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

前端 未结 10 591
無奈伤痛
無奈伤痛 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:17

    New answer to an old question. Rationale for new answer: In case you want to use types to solve a problem like this.

    In addition to C++11/C++14, you'll need this free, open source date/time library:

    #include "tz.h"
    #include 
    #include 
    
    int
    main()
    {
        std::istringstream is("2010-11-04T23:23:01Z");
        is.exceptions(std::ios::failbit);
        date::sys_seconds tp;
        date::parse(is, "%FT%TZ", tp);
        std::cout << "seconds from epoch is " << tp.time_since_epoch().count() << "s\n";
    }
    

    This program outputs:

    seconds from epoch is 1288912981s
    

    If the parse fails in any way, an exception will be thrown. If you would rather not throw exceptions, don't is.exceptions(std::ios::failbit);, but instead check for is.fail().

提交回复
热议问题