Search code examples
c++timeepoch

convert time string to epoch in milliseconds using C++


I try to convert the following time string to epoch in milliseconds

"2022-09-25T10:07:41.000Z"

i tried the following code which outputs only epoch time in seconds (1661422061) how to get the epoch time in milliseconds.

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

int main()
{
    int tt;
    std::tm t = {};
    std::string timestamp = "2022-09-25T10:07:41.000Z";
    std::istringstream ss(timestamp);

    if (ss >> std::get_time(&t, "%Y-%m-%dT%H:%M:%S.000Z"))
    {
        tt = std::mktime(&t);
        std::cout << std::put_time(&t, "%c") << "\n"
                  << tt << "\n";
    }
    else
    {
        std::cout << "Parse failed\n";
    }
    return 0;
}

Solution

  • You can use the C++20 features std::chrono::parse / std::chrono::from_stream and set the timepoint to be in milliseconds.

    A modified example from my error report on MSVC on this subject which uses from_stream:

    #include <chrono>
    #include <iostream>
    #include <locale>
    #include <sstream>
    
    int main() {
        std::setlocale(LC_ALL, "C");
        std::istringstream stream("2022-09-25T10:07:41.123456Z");
    
        std::chrono::sys_time<std::chrono::milliseconds> tTimePoint;
        std::chrono::from_stream(stream, "%Y-%m-%dT%H:%M:%S%Z", tTimePoint);
    
        std::cout << tTimePoint << '\n';
        
        auto since_epoch = tTimePoint.time_since_epoch();
        std::cout << since_epoch << '\n';                 // 1664100461123ms
    
        // or as                                             1664100461.123s
        std::chrono::duration<double> fsince_epoch = since_epoch;
        std::cout << std::fixed << std::setprecision(3) << fsince_epoch << '\n';
    }
    

    Demo


    If you are stuck with C++11 - C++17 you can install the date library by Howard Hinnant. It's the base of what got included in C++20 so if you upgrade to C++20 later, you will not have many issues.

    #include "date/date.h"
    
    #include <chrono>
    #include <iostream>
    #include <sstream>
    
    int main() {
        std::istringstream stream("2022-09-25T10:07:41.123456Z");
    
        date::sys_time<std::chrono::milliseconds> tTimePoint;
        date::from_stream(stream, "%Y-%m-%dT%H:%M:%S%Z", tTimePoint);
    
        auto since_epoch = tTimePoint.time_since_epoch();
    
        // GMT: Sunday 25 September 2022 10:07:41.123
        std::cout << since_epoch.count() << '\n'; // prints 1664100461123
    }