Skip to content

Instantly share code, notes, and snippets.

@ashwin
Created January 13, 2015 04:13
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ashwin/2c610a89fd184625faf3 to your computer and use it in GitHub Desktop.
Save ashwin/2c610a89fd184625faf3 to your computer and use it in GitHub Desktop.
Get and print current date and time in C++
// 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;
@sunapi386
Copy link

You missed #include <sstream>

@ol3h-unag1
Copy link

ol3h-unag1 commented Jan 6, 2021

visual studio 2019 aint allowing to build code with localtime without disabling CRT warnings

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment