所以现在,我正在使用的代码是
using std::chrono::system_clock;
std::time_t tt = system_clock::to_time_t (system_clock::now());
struct std::tm * ptm = std::localtime(&tt);
std::cout << "Current time: " << std::put_time(ptm,"%X") << '\n';
std::this_thread::sleep_for (std::chrono::seconds(7));
这很简单,因为它处于循环中,并且chrono sleep_for将系统延迟多秒。问题是当我真的需要seconds.milliseconds来显示系统时钟事务时间时,它采用HH:MM:SS格式。我该怎么做?我真的只需要一个人来解释代码,为什么要构造一个结构?我应该怎么做才能改变格式?谢谢!
我为您提供了两个答案:
明年如何执行此操作(在C ++ 20中,今天尚未实现,并且
今天如何进行一些小的语法更改和open-source 3rd party library。
第一个1:
#include <chrono>
#include <iostream>
#include <thread>
int
main()
{
using namespace std::chrono;
auto tp = system_clock::now();
while (true)
{
zoned_time zt{current_zone(), floor<milliseconds>(system_clock::now())};
cout << "Current time: " << std::format("{:%T}", zt) << '\n';
tp += 7s;
std::this_thread::sleep_until (tp);
}
}
这将使用计算机当前设置的时区创建一个本地时间,精度为毫秒。然后仅以所需的格式(%T)将其打印出来。我使用的是sleep_until
而不是sleep_for
,这样循环的每次迭代都不会由于循环开销而偏离所需的7s间隔。
第二个:
还没有人,但是您今天可以用Howard Hinnant's free open source date/time library进行近似:
#include "date/tz.h"
#include <chrono>
#include <iostream>
#include <thread>
int
main()
{
using namespace date;
using namespace std::chrono;
auto tp = system_clock::now();
while (true)
{
zoned_time zt{current_zone(), floor<milliseconds>(system_clock::now())};
cout << "Current time: " << format("%T", zt) << '\n';
tp += 7s;
std::this_thread::sleep_until (tp);
}
}
不同之处在于format
语句略有不同,并且库位于namespace date
而不是namespace std::chrono
中。并且要包含一个额外的标题。和some installation is required to handle the time zones。
如果您对UTC时间戳而不是本地时间戳感到满意,则可以使用相同库的仅标头版本,如下所示(无需安装):
#include "date/date.h"
#include <iostream>
#include <thread>
int
main()
{
auto tp = std::chrono::system_clock::now();
while (true)
{
using namespace date;
using namespace std::chrono;
std::cout << "Current time: "
<< format("%T", floor<milliseconds>(system_clock::now())) << '\n';
tp += 7s;
std::this_thread::sleep_until (tp);
}
}