繁体   English   中英

有没有更简单的方法以 hh:mm:ss 格式获取当前时间?

[英]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::chronostd::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, &ltime);
    std::cout << std::put_time(&ltime, "%H:%M:%S") << std::endl;
}

编译和运行:

$ clang++ -std=c++11 so.cpp
$ ./a.out
13:44:23
$

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM