Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How print current time in C++11?

Tags:

Is there an easy way in C++11 to print the current wall time using the appropriate formatting rules of the locale associated with the ostream being used?

What I really want to do is something like this:

myStream << std::chrono::system_clock::now(); 

and have the date and time printed in accord with whatever locale is associated with myStream. C++11 offers put_time, but it takes a formatting string, and I want the format to be determined by the locale associate with the stream. There's also time_put and time_put_byname, but based on the examples at cppreference.com, these functions are used in conjunction with put_time.

Is there no simple way to print a timepoint value without manually formatting it?

like image 762
KnowItAllWannabe Avatar asked Jul 23 '13 17:07

KnowItAllWannabe


People also ask

How to print the current date and time in C++?

In C++ 11, we can also use std::chrono::system_clock::now (), which returns a time point representing the current point in time. That’s all about printing the current date and time in C.

How to get the current date and time in C++ 11?

Following is a simple C implementation to get the current date and time –. In C++ 11, we can also use std::chrono::system_clock::now () which returns a time point representing the current point in time.

Which library is used to print current date and time?

Here we have used chrono library to print current date and time . The chrono library is a flexible collection of types that tracks time with varying degrees of precision . The chrono library defines three main types as well as utility functions and common typedefs.

What is the use of time_t in C?

The time_t is not a primitive data type, rather it is a data type from the C ISO library define to store system's time value. This system's time values are returned from the standard library function named time (). The function ctime () returns a string that represents the local time based on tm (argument) timer.


1 Answers

You can use put_time with a format string like "%c". %c is the format specifier for the standard date and time string for the locale. The result looks like "Tue Jul 23 19:32:18 CEST 2013" on my machine (POSIX en_US locale, in a German timezone).

auto now = std::chrono::system_clock::now(); auto now_c = std::chrono::system_clock::to_time_t(now); std::cout << std::put_time(std::localtime(&now_c), "%c") << '\n'; 
like image 177
R. Martinho Fernandes Avatar answered Nov 01 '22 22:11

R. Martinho Fernandes