Created
January 13, 2015 04:13
-
-
Save ashwin/2c610a89fd184625faf3 to your computer and use it in GitHub Desktop.
Get and print current date and time in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |
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
You missed
#include <sstream>