如果精确到秒的时间足够准确,您strftime
可以使用
#include <ctime>
#include <iostream>
<br/>
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";
}
如果您需要更高的精度,可以使用 Boost。
#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
<br/>
int main() {
using namespace boost::posix_time;
ptime t = microsec_clock::universal_time();
std::cout << to_iso_extended_string(t) << "Z\n";
}
使用日期库 (C++11):
template <class Precision>
string getISOCurrentTimestamp()
{
auto now = chrono::system_clock::now();
return date::format("%FT%TZ", date::floor<Precision>(now));
}
例子:
cout << getISOCurrentTimestamp<chrono::seconds>();
cout << getISOCurrentTimestamp<chrono::milliseconds>();
cout << getISOCurrentTimestamp<chrono::microseconds>();
输出:
2022-09-09T15:07:37Z
2022-09-09T15:07:37.035Z
2022-09-09T15:07:37.035332Z