c ++ and get GMT time string

Need cross-platform, so the only alternative std and boost:

boost more complicated

#include <boost/date_time/local_time/local_time.hpp>

std::string gmt_time_now() {
  boost::local_time::time_zone_ptr GMT_zone(
      new boost::local_time::posix_time_zone("GMT"));
  auto now = boost::local_time::local_microsec_clock::local_time(GMT_zone);

  std::stringstream ss;


  auto* output_facet = new boost::local_time::local_time_facet();

  auto* input_facet = new boost::local_time::local_time_input_facet();
  output_facet->format("%Y-%m-%dT%H:%M:%SZ");
  ss.imbue(std::locale(std::locale::classic(), output_facet));
  ss.imbue(std::locale(ss.getloc(), input_facet));
  ss << now;

  return ss.str();
}

There is an easier method chrono std

std::string gmt_time_now() {
  /**
   * Generate a UTC ISO8601-formatted timestamp
   * and return as std::string
   */
  auto now = std::chrono::system_clock::now();
  auto itt = std::chrono::system_clock::to_time_t(now);

  std::ostringstream ss;
  ss << std::put_time(gmtime(&itt), "%FT%TZ");
  return ss.str();
}

The need to support c ++ 11

Guess you like

Origin www.cnblogs.com/hustcpp/p/12155754.html