简体   繁体   English

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

[英]Is there an easier way to get the current time in hh:mm:ss format?

I tried to print the current time in the usual format of hh:mm:ss however I get the full date format instead.我尝试以通常的 hh:mm:ss 格式打印当前时间,但是我得到了完整的日期格式。 I need the answer to be in string or int, so it is easier to deal with.我需要答案是字符串或整数,所以更容易处理。 I was thinking of adding it to a log file so that I can make it easier to track my program.我正在考虑将其添加到日志文件中,以便更轻松地跟踪我的程序。

#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";
}

I do want a little tip to help me do so.我确实想要一些小费来帮助我这样做。

Using std::chrono and std::format :使用std::chronostd::format

  • You can just pass a time_point and format it according to a format specification .您可以只传递一个time_point并根据格式规范对其进行格式化。 In the example below %T is equivalent to %H:%M:%S (hours in 24-hour clock, and minutes and seconds using 2 digits).在下面的示例中, %T等价于%H:%M:%S (24 小时制中的小时,以及使用 2 位数字的分钟和秒)。
  • If you don't want to print out microseconds, you can floor the current time.如果您不想打印出微秒,您可以将当前时间设置为floor

Note std::format requires C++20.注意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()));
}

The following example displays the time in the "HH:MM:SS" format (requires at least c++11 - tested with clang):以下示例以“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;
}

Compiling and running:编译和运行:

$ 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