Search code examples
c++linuxgccc++20unix-timestamp

Convert UTC string datetime into millisecond UTC timestamp


In C++20, under UNIX systems (no portability is required), how do I convert a UTC string date time of the following format:

"2024-04-26T14:33:30.185Z"

into a UNIX UTC numeric timestamp ?

I am looking for the standard recommended way, if there is any.

There are many answers for similar questions, but they seem to either provide solutions for older standards, or focus on portability, or require time zone conversion. I am looking for the simple efficient standard way to do this under Linux with C++20, without portability requirement and without time zone conversion.


Solution

  • In C++20:

    #include <chrono>
    #include <iostream>
    #include <sstream>
    
    int
    main()
    {
       std::string s = "2024-04-26T14:33:30.185Z";
       std::istringstream f(std::move(s));
       std::chrono::sys_time<std::chrono::milliseconds> tp;
       f >> std::chrono::parse("%FT%TZ", tp);
       std::cout << tp.time_since_epoch().count() << '\n';
    }
    

    Output:

    1714142010185
    

    Demo.

    This parses the string into a system_clock-based time_point with milliseconds precision. system_clock measures Unix Time (time since 1970-01-01 00:00:00 UTC excluding leap seconds). Here is the spec for the system_clock epoch.

    std::chrono::utc_time differs from sys_time only in that it includes the count of leap seconds: http://eel.is/c++draft/time.clock#utc.overview-1

    The .time_since_epoch().count() extracts the integral number of milliseconds from this time_point.

    Unfortunately this has yet to ship in gcc, but will ship in gcc-14. There exists an open-source, free, header-only pre-C++20-chrono preview of this library here: https://github.com/HowardHinnant/date

    Just include "date/date.h" and change a few std::chrono to date.