How do I construct an ISO 8601 datetime in C++?

前端 未结 9 1242
小蘑菇
小蘑菇 2020-12-05 01:51

I\'m working with the Azure REST API and they are using this to create the request body for table storage:

DateTime.UtcNow.ToString(\"o\")

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 02:23

    You can use this function which uses std::put_time with a std::ostringstream to generate the resulting std::string.

    #include 
    #include 
    #include 
    #include 
    /**
     * Generate a UTC ISO8601-formatted timestamp
     * and return as std::string
     */
    std::string currentISO8601TimeUTC() {
      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();
    }
    // Usage example
    int main() {
        std::cout << currentISO8601TimeUTC() << std::endl;
    }
    

    Reference: https://techoverflow.net/2018/03/30/iso8601-utc-time-as-stdstring-using-c11-chrono/

提交回复
热议问题