[英]Is there an easier way to get the current time in hh:mm:ss format?
我尝试以通常的 hh:mm:ss 格式打印当前时间,但是我得到了完整的日期格式。 我需要答案是字符串或整数,所以更容易处理。 我正在考虑将其添加到日志文件中,以便更轻松地跟踪我的程序。
#include <iostream>
#include <chrono>
#include <ctime>
int main()
{
auto curr_time = std::chrono::system_clock::now();
std::time_t pcurr_time = std::chrono::system_clock::to_time_t(curr_time);
std::cout << "current time" << std::ctime(&pcurr_time)<<"\n";
}
我确实想要一些小费来帮助我这样做。
使用std::chrono
和std::format
:
time_point
并根据格式规范对其进行格式化。 在下面的示例中, %T
等价于%H:%M:%S
(24 小时制中的小时,以及使用 2 位数字的分钟和秒)。floor
。 注意std::format
需要 C++20。
#include <chrono>
#include <format>
#include <iostream> // cout
int main(int argc, const char* argv[])
{
namespace ch = std::chrono;
std::cout << std::format("{:%T}", ch::floor<ch::seconds>(ch::system_clock::now()));
}
以下示例以“HH:MM:SS”格式显示时间(至少需要 c++11 - 使用 clang 测试):
#include <iostream>
#include <iomanip>
#include <chrono>
#include <ctime>
int main()
{
std::time_t t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::tm ltime;
localtime_r(&t, <ime);
std::cout << std::put_time(<ime, "%H:%M:%S") << std::endl;
}
编译和运行:
$ clang++ -std=c++11 so.cpp
$ ./a.out
13:44:23
$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.