c++ 獲取GMT 時間和字符串


需要跨平台,所以可選的只有std 和 boost:

boost 比較復雜了

#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();
}

還有更簡便的std 方法 chrono

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();
}

需要支持 c++11


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM