This post will discuss how to get the current time and date in C++.

1. Using std::chrono

Since C++11, the standard solution to get the current time and date in C++ is using chrono library. We can get the current time with std::chrono::system_clock::now() from the <chrono.h> header, and convert it to a std::time_t type (time since epoch). Then, convert the std::time_t to a local calendar time std::ctime in Www Mmm dd hh:mm:ss yyyy format, as shown below:

Download  Run Code

Output (will vary):

Current Time and Date: Tue Feb 08 18:40:13 2018

 
If you just need to measure elapsed time in C++, do as follows.

Download  Run Code

Output (will vary):

Elapsed Time: 0.060156 sec

 
Since C++20, we can also use std::chrono::zoned_time for representing date and time with a time-zone.

Download Code

2. Using std::time

The idea is to get the number of seconds elapsed since epoch as std::time_t value, and then convert it into an std::tm instance with std::localtime. An std::tm object holds a calendar date and time broken down into its components (sec, min, hour, day, month, year, etc.).

The following code example demonstrates its usage. Note that this solution needs <ctime> header.

Download  Run Code

Output (will vary):

Current Date: 8/2/2018

 
We can further convert date and time information from the std::tm object to a null-terminated multibyte character, according to the specified format string using the strftime() function. For example, the following code returns the current date and time as std::string in the format MM-DD-YYYY HH:mm:ss.

Download  Run Code

Output (will vary):

Current Time and Date: 02-08-2018 18:42:41

3. Using Boost.Date_Time

Another option is to use the date-time functions offered by the boost library. There are several time systems available by boost library. The following solution uses boost::posix_time::microsec_clock::universal_time from the header <boost/date_time/posix_time/posix_time> – that return the time in UTC.

Download Code

Output (will vary):

Current Time and Date: 2018-Feb-08 18:42:41.804879

That’s all about getting the current time and date in C++.