Getting Current Time and Date in C Cross-Platform
The C standard library now provides a convenient and portable way to retrieve the current time and date through the std::chrono::system_clock class. Introduced in C 11, this class offers a system-independent interface for accessing high-resolution timing information.
Syntax:
auto now = std::chrono::system_clock::now();
The now() function returns a time_point object representing the current moment in time. Time points can be manipulated and compared to calculate elapsed time or retrieve specific date and time components.
Example:
#include <iostream> #include <chrono> int main() { auto now = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = now - std::chrono::system_clock::now(); std::cout << "Current time: " << std::ctime(&now) << std::endl; std::cout << "Elapsed seconds: " << elapsed_seconds.count() << std::endl; }
This example prints output similar to:
Current time: Mon Oct 2 00:59:08 2017 Elapsed seconds: 0.000372
Additionally, std::chrono provides utility functions to extract specific date and time components, such as:
By combining std::chrono with C standard library functions, you have a comprehensive cross-platform solution for handling date and time operations in your C applications.
The above is the detailed content of How Can I Get the Current Time and Date in C Cross-Platform?. For more information, please follow other related articles on the PHP Chinese website!