c++datetimec++14cross-platformepoch

Format Date and Time As Per User's Locale Settings using C++ Libraries


I want to extract date and time from an Epoch value and convert as per User's Locale Settings . There is already an existing solution using Windows API https://www.codeproject.com/Articles/12568/Format-Date-and-Time-As-Per-User-s-Locale-Settings

I want same thing to be platform independent. (Mac / Windows / Linux) How can I achieve this? Are there any C/C++ libraries to do the same? I am using C++14.


Solution

  • As pointed out by @IgorTandetnik in the comments, here is the sample code to do the following:

    #include <iostream>
    #include <iomanip>
    #include <ctime>
    
    int main() {
        // Epoch value (in seconds since January 1, 1970)
        std::time_t epochValue = std::time(nullptr);
    
        // Convert the epoch value to a struct tm representing local time
        std::tm* localTime = std::localtime(&epochValue);
    
        // Set locale settings for cout
        std::cout.imbue(std::locale(""));
    
        // Print the formatted date and time according to the user's locale settings
        std::cout << std::put_time(localTime, "%x %X") << std::endl;
    
        return 0;
    }