【问题标题】:Get date and time in UTC format in c++ [duplicate]在c ++中以UTC格式获取日期和时间[重复]
【发布时间】:2020-10-12 18:56:42
【问题描述】:

如何在 C++ 中以这种格式 ('2002-05-30T09:30:10Z') 获取 UTC 时间的日期时间? 这是我做的函数。

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

此函数现在以这种格式打印“UTC 日期和时间是:Mon Oct 12 18:56:59 2020”。

【问题讨论】:

    标签: c++ c++11 visual-c++ c++17


    【解决方案1】:

    使用这个free, open-source, header-only preview of C++20 &lt;chrono&gt;

    #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';
    }
    

    这将通过以下方式轻松移植到 C++20:

    • 删除#include "date/date.h"
    • date::format 更改为std::format
    • "%FT%TZ" 更改为"{:%FT%TZ}"

    【讨论】:

    • 当我使用 std::format 时,它给了我一个错误,即命名空间 std 没有成员格式。
    • 现在您必须使用free, open-source, header-only preview of C++20 &lt;chrono&gt;。供应商仍在努力实现 C++20。
    • 现在当我使用 date::format 时,我收到此错误“C++ 名称后跟 '::' 必须是类或命名空间名称”
    • 如果您完整显示 first 错误,我可以提供帮助。
    • 不是“{%FT%TZ}”而是“{:%FT%TZ}”
    猜你喜欢
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多