Search code examples
c++stringunix-timestampc++-chronoiso8601

Convert unix microseconds to ISO 8601 date time string in C++


Problem:

I got a signed integer 64-bit variable of unix time with microseconds. I want to convert that to ISO 8601 Date time format. The format must be stored in a string in C++.

Notice that this is microseconds and not seconds and the output must be a string and not stream.

I begin with my time point

std::chrono::system_clock::time_point timePoint

Which I convert to microseconds in unix time.

std::chrono::system_clock::duration duration = timePoint.time_since_epoch();
int64_t microsecondsUnixTime = duration.count()/10;

And now I need to convert microsecondsUnixTime to date time in the format ISO 8601 as a string only.


Solution

  • If you divide microsecondsUnixTime by 106 you can use std::strftime() to generate the string to 1 second resolution, then append the fractional part for microsecond resolution:

    int fraction_sec = microsecondsUnixTime % 1000000u ;
    time_t seconds = microsecondsUnixTime / 1000000u ;
    
    char timestr_sec[] = "YYYY-MM-DD hh:mm:ss.ssssss" ;
    std::strftime( timestr_sec, sizeof(timestr_sec) - 1, 
                   "%F %T", std::gmtime(&seconds) ) ;
    std::ostringstream  tout ;
    tout << timestr_sec << '.' << std::setfill('0') << std::setw(6) << fraction_sec ;    
    std::string timestr_micro = tout.str() ;
    
    std::cout << timestr_micro ;
    

    Output example:

    2022-12-07 20:25:18.860289