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

前端 未结 9 1231
小蘑菇
小蘑菇 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:24

    If the time to the nearest second is precise enough, you can use strftime:

    #include 
    #include 
    
    int main() {
        time_t now;
        time(&now);
        char buf[sizeof "2011-10-08T07:07:09Z"];
        strftime(buf, sizeof buf, "%FT%TZ", gmtime(&now));
        // this will work too, if your compiler doesn't support %F or %T:
        //strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M:%SZ", gmtime(&now));
        std::cout << buf << "\n";
    }
    

    If you need more precision, you can use Boost:

    #include 
    #include 
    
    int main() {
        using namespace boost::posix_time;
        ptime t = microsec_clock::universal_time();
        std::cout << to_iso_extended_string(t) << "Z\n";
    }
    

提交回复
热议问题