将当前日期精确到毫秒
Get current date down to milliseconds
本文关键字:当前日期 更新时间:2023-10-16
我需要以可打印格式获得当前UTC日期,在c++11中精确到毫秒。我需要这个在Windows和Linux上运行,所以跨平台代码是首选。如果这是不可能的,我可以写两个单独的实现。
这是我尝试过的:
std::chrono::time_point<std::chrono::high_resolution_clock> time = std::chrono::system_clock::now();
std::time_t tt = std::chrono::high_resolution_clock::to_time_t(time);
struct tm* utc = nullptr;
gmtime_s(utc, &tt);
char buffer[256];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%dT-%H:%M:%S. %MILLESECONDS???, utc);
虽然你可以看到,这并没有得到它到毫秒。如果需要,我可以自己格式化字符串只要我能得到毫秒值。
time_t只包含秒数,因此您可以使用std::chrono函数来获得更高的精度:
#include <iostream>
#include <chrono>
int main()
{
typedef std::chrono::system_clock clock_type;
auto now = clock_type::now();
auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
auto fraction = now - seconds;
time_t cnow = clock_type::to_time_t(now);
auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(fraction);
std::cout << "Milliseconds: " << milliseconds.count() << 'n';
}
相关文章:
- 使程序检查当前日期是否=预期日期
- 日期和当前日期之间的差异
- 仅使用C++中的标准库获取以毫秒为单位的当前日期和时间
- 从当前日期C++中减去任意日期
- 计算当前日期和用户输入日期问题之间的天数
- 在 C++20 中获取当前日期/时间是否线程安全?
- 以C++/提升表示 ISO 8601 持续时间,具体取决于当前日期
- 标准::时间 将天数添加到当前日期
- 符合C++的实现如何指示它不知道当前日期和时间?
- C 获得当前日期
- 如何在当前日期/时间之后命名我创建的文本文件
- 将当前日期与 c++ 中的 sql 数据库条目匹配
- 如何在 c++ 中获取当前日期
- TDateTime变量中的当前日期/时间
- Qt - 以 mmmm YYYY 格式获取当前日期(作为字符串)
- 获取C++的当前日期和时间
- 可视化如何在C++程序中获取当前日期
- 从时钟获取当前日期
- C++11 获取当前日期和时间作为字符串
- 如何在ROS中查找计算机的当前日期