'Get date and time in UTC format in c++ [duplicate]

How can I get a datetime in UTC time in this format ('2002-05-30T09:30:10Z') in C++? This is the function I have made.

void settime(){
      // Current date/time based on current system
  time_t now = time(0);
   
  // Convert now to tm struct for local timezone
  tm* localtm = localtime(&now);
  cout << "The local date and time is: " << asctime(localtm) << endl;

  // Convert now to tm struct for UTC
  tm* gmtm = gmtime(&now);
  if (gmtm != NULL) {
     cout << "The UTC date and time is: " << asctime(gmtm) << endl;
  }
  else {
    cerr << "Failed to get the UTC date and time" << endl;
  
  } 
}

This function print in this format 'The UTC date and time is: Mon Oct 12 18:56:59 2020' right now.



Solution 1:[1]

Using this free, open-source, header-only preview of C++20 <chrono>:

#include "date/date.h"
#include <chrono>
#include <iostream>

int
main()
{
    namespace cr = std::chrono;
    std::cout << date::format("%FT%TZ", cr::floor<cr::seconds>(cr::system_clock::now())) << '\n';
}

This will easily port to C++20 by:

  • Drop #include "date/date.h"
  • Change date::format to std::format
  • Change "%FT%TZ" to "{:%FT%TZ}"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1