我正在使用Azure REST API,他们正在使用它来创建表存储的请求主体:
DateTime.UtcNow.ToString("o")
Run Code Online (Sandbox Code Playgroud)
哪个产生:
2012-03-02T04:07:34.0218628Z
它被称为"往返",显然它是一个ISO标准(见http://en.wikipedia.org/wiki/ISO_8601),但我不知道如何在阅读维基文章后复制它.
str*_*cat 66
如果到最近的秒的时间足够精确,您可以使用strftime:
#include <ctime>
#include <iostream>
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";
}
Run Code Online (Sandbox Code Playgroud)
如果您需要更高的精度,可以使用Boost:
#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
int main() {
using namespace boost::posix_time;
ptime t = microsec_clock::universal_time();
std::cout << to_iso_extended_string(t) << "Z\n";
}
Run Code Online (Sandbox Code Playgroud)
Gil*_*pie 25
使用日期库(C++ 11):
template <class Precision>
string getISOCurrentTimestamp()
{
auto now = chrono::system_clock::now();
return date::format("%FT%TZ", date::floor<Precision>(now));
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
cout << getISOCurrentTimestamp<chrono::seconds>();
cout << getISOCurrentTimestamp<chrono::milliseconds>();
cout << getISOCurrentTimestamp<chrono::microseconds>();
Run Code Online (Sandbox Code Playgroud)
输出:
2017-04-28T15:07:37Z
2017-04-28T15:07:37.035Z
2017-04-28T15:07:37.035332Z
Run Code Online (Sandbox Code Playgroud)
Syn*_*nck 24
对于 C++20,时间点格式(字符串)可在 (chrono) 标准库中使用。 https://en.cppreference.com/w/cpp/chrono/system_clock/formatter
#include <chrono>
#include <format>
#include <iostream>
int main()
{
const auto now = std::chrono::system_clock::now();
std::cout << std::format("{:%FT%TZ}", now) << '\n';
}
Run Code Online (Sandbox Code Playgroud)
输出
2021-11-02T15:12:46.0173346Z
Run Code Online (Sandbox Code Playgroud)
它适用于具有最新 C++ 语言版本 (/std:c++latest) 的 Visual Studio 2019。
在 Qt 中,这将是:
QDateTime dt = QDateTime::currentDateTime();
dt.setTimeSpec(Qt::UTC); // or Qt::OffsetFromUTC for offset from UTC
qDebug() << QDateTime::currentDateTime().toString(Qt::ISODate);
Run Code Online (Sandbox Code Playgroud)
我应该指出我是C ++新手。
我需要UTC ISO 8601格式的日期和时间(包括毫秒)的字符串。我没有机会提高。
这更多的是破解而不是解决方案,但对我来说效果很好。
std::string getTime()
{
timeval curTime;
time_t now;
time(&now);
gettimeofday(&curTime, NULL);
int milli = curTime.tv_usec / 1000;
char buf[sizeof "2011-10-08T07:07:09.000Z"];
strftime(buf, sizeof buf, "%FT%T", gmtime(&now));
sprintf(buf, "%s.%dZ", buf, milli);
return buf;
}
Run Code Online (Sandbox Code Playgroud)
输出看起来像:2016-04-13T06:53:15.485Z
| 归档时间: |
|
| 查看次数: |
43156 次 |
| 最近记录: |