Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
$
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading