11

How can I print the current time using the std::chrono library?

I would like the format to be: hour:minute:second:millisecond:microsecond:nanosecond.

13

1 Answer 1

24

[EDIT]

Changing the code to C++ style:

#include <chrono>
#include <ctime>

std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
auto duration = now.time_since_epoch();

typedef std::chrono::duration<int, std::ratio_multiply<std::chrono::hours::period, std::ratio<8>
>::type> Days; /* UTC: +8:00 */

Days days = std::chrono::duration_cast<Days>(duration);
    duration -= days;
auto hours = std::chrono::duration_cast<std::chrono::hours>(duration);
    duration -= hours;
auto minutes = std::chrono::duration_cast<std::chrono::minutes>(duration);
    duration -= minutes;
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration);
    duration -= seconds;
auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
    duration -= milliseconds;
auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(duration);
    duration -= microseconds;
auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(duration);

std::cout << hours.count() << ":"
          << minutes.count() << ":"
          << seconds.count() << ":"
          << milliseconds.count() << ":"
          << microseconds.count() << ":"
          << nanoseconds.count() << std::endl;

Result:

17:56:14:94:451:679

[Old]

A simply example:

#include <sys/time.h>

char fmt[64];
char buf[64];
struct timeval tv;
struct tm *tm;

gettimeofday (&tv, NULL);
tm = localtime (&tv.tv_sec);
strftime (fmt, sizeof (fmt), "%H:%M:%S:%%06u", tm);
snprintf (buf, sizeof (buf), fmt, tv.tv_usec);
printf ("%s\n", buf);

Result:

00:01:32:695240
12
  • Thank you. But, may i please know what is %%06u. Is it possible to get microseconds in same format? Dec 28, 2014 at 16:13
  • 9
    —1: Where is the std::chrono usage here? This is some C nonsense from 120 years ago! Dec 28, 2014 at 16:14
  • @LightnessRacesinOrbit: Thanks, the code is really old. I wrote it few years ago. I already modified the code into new C++11 style.
    – Kir Chou
    Dec 28, 2014 at 18:06
  • You don't like C++ very much, do you? :) +1 Dec 28, 2014 at 18:06
  • 1
    @user3665224 time_point will return the value from (1970.01.01 00:00:00 UTC) to present. To be human-readable, value should minus (Today 00:00 UTC). You need to manipulate it by yourself, because I don't know your UTC time.
    – Kir Chou
    Dec 28, 2014 at 19:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.