Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to get date and time in C++

📅 2015-Jan-13 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, date, time ⬩ 📚 Archive

In C++11 and later versions, date and time is supported in the standard library through the chrono header file. To print out the date and time, you may still have to fall back on the std::time_t and std::tm structures and std::ctime and std::localtime functions from the ctime header file and std::put_time from iomanip header file.

The code sample below shows these in action:

// Example output from this code:
// Tue Jan 13 12:09:53 2015 (from ctime)
// 20150113_12_09_53 (from strftime)
// 20150113_12_09_53 (from put_time)

#include <ctime>
#include <chrono>
#include <iomanip>

// Get current time
std::chrono::time_point<std::chrono::system_clock> time_now = std::chrono::system_clock::now();

// Print time using ctime
std::time_t time_now_t = std::chrono::system_clock::to_time_t(time_now);
std::cout << std::ctime(&time_now_t) << std::endl;

// Format time and print using strftime
std::tm now_tm = *std::localtime(&time_now_t);
char buf[512];
std::strftime(buf, 512, "%Y%m%d_%H_%M_%S", &now_tm);
std::cout << buf << std::endl;

// Format time and print using put_time
std::stringstream ss;
ss << std::put_time(&now_tm, "%Y%m%d_%H_%M_%S");
std::cout << ss.str() << std::endl;

Tried with: Visual C++ 2013

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘📧