Home >Backend Development >C++ >How Do I Get the Current Date and Time in C ?
How to Obtain the Current Time and Date in C
In C , there's a platform-independent approach to retrieving the current date and time:
std::chrono::system_clock::now()
Introduced in C 11, this function provides a portable method to access the system clock's current time. Here's an example adapted from en.cppreference.com:
#include <iostream> #include <chrono> #include <ctime> int main() { auto start = std::chrono::system_clock::now(); // Some computation auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "Finished computation at " << std::ctime(&end_time) << "Elapsed time: " << elapsed_seconds.count() << "s" << std::endl; }
This code will output a timestamp similar to:
Finished computation at Mon Oct 2 00:59:08 2017 Elapsed time: 1.88232s
The above is the detailed content of How Do I Get the Current Date and Time in C ?. For more information, please follow other related articles on the PHP Chinese website!