简体   繁体   中英

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. 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 :

  • You can just pass a time_point and format it according to a format specification . In the example below %T is equivalent to %H:%M:%S (hours in 24-hour clock, and minutes and seconds using 2 digits).
  • If you don't want to print out microseconds, you can floor the current time.

Note std::format requires 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):

#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
$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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