Home >Backend Development >C++ >How to display the current time in c++
Several methods to display the current time in C: use time() to obtain the timestamp, use the std::chrono class to obtain the system time, use a third-party library (such as Boost.Date_Time)
How to display the current time in C
There are several ways to display the current time in C:
1. Use the standard library function time()
<code class="cpp">#include <iostream> #include <ctime> int main() { time_t now = time(0); std::cout << "Current time: " << ctime(&now); return 0; }</code>
2. Use the class std::chrono
<code class="cpp">#include <iostream> #include <chrono> int main() { auto now = std::chrono::system_clock::now(); auto time_t_now = std::chrono::system_clock::to_time_t(now); std::cout << "Current time: " << ctime(&time_t_now); return 0; }</code>
3. Use third-party libraries
There are many third-party libraries that can help you display the current time, such as Boost.Date_Time:
<code class="cpp">#include <iostream> #include <boost/date_time/posix_time/posix_time.hpp> int main() { boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); std::cout << "Current time: " << now; return 0; }</code>
The above is the detailed content of How to display the current time in c++. For more information, please follow other related articles on the PHP Chinese website!