Search code examples
c++c++17c++-chrono

Convert from UTC date string to Unix timestamp and back


How to convert from string like “2021-11-15 12:10" in UTC to Unix timestamp?

Then add two hours to timestamp (like timestamp += 60*60*2).

Then convert resulting timestamp to string in the same format in UTC?

Using <chrono>, <ctime>, or library, doesn’t really matter.


Solution

  • You could use the I/O manipulators std::get_time and std::put_time.

    Example:

    #include <ctime>
    #include <iomanip>
    #include <iostream>
    #include <sstream>
    
    int main() {
        std::istringstream in("2021-11-15 12:10"); // put the date in an istringstream
        
        std::tm t{};
        t.tm_isdst = -1; // let std::mktime try to figure out if DST is in effect
    
        in >> std::get_time(&t, "%Y-%m-%d %H:%M"); // extract it into a std::tm
        
        std::time_t timestamp = std::mktime(&t);   // get epoch
    
        timestamp += 2 * 60 *60;                   // add 2 hours
    
        std::tm utc = *std::gmtime(&timestamp);    // make a UTC std::tm
        std::tm lt = *std::localtime(&timestamp);  // make a localtime std::tm
        
        // print the results:
        std::cout << std::put_time(&utc, "%Y-%m-%d %H:%M") << '\n'
                  << std::put_time(&lt, "%Y-%m-%d %H:%M") << '\n';
    }