C++ Date and Time

C++ Tutorial

⏰ C++ Date and Time

C++ provides date and time support mainly through the C-style <ctime> library and modern C++ <chrono> library.
Both are important, but <chrono> is preferred in modern C++.


🔹 1. C-Style Date & Time (<ctime>)

Include Header

#include <ctime>

🔹 2. Get Current Date and Time


 


🔹 3. Convert Time to Readable Format


 

Output example:

Tue Dec 16 10:35:22 2025

🔹 4. Using tm Structure (Break Date & Time)


 


🔹 5. GMT / UTC Time

tm* gmtTime = gmtime(&now);

✔ Returns UTC time instead of local time


🔹 6. Format Date & Time (strftime)


 

Common format codes:

CodeMeaning
%YYear
%mMonth
%dDay
%HHour
%MMinute
%SSecond

🔹 7. Modern CPP Date & Time (<chrono>) ✅

Include Header

#include <chrono>

Get Current Time (System Clock)


 


🔹 8. Convert chrono Time to time_t


 


🔹 9. Measure Execution Time (Very Common)


 


🔹 10. Sleep / Delay

#include <thread>
#include <chrono>
this_thread::sleep_for(chrono::seconds(2));

✔ Pauses program for 2 seconds


🔁 <ctime> vs <chrono>

<ctime><chrono>
Old (C-style)Modern C++
Easy to useMore powerful
Less preciseHigh precision
Not type-safeType-safe

📌 Summary

  • <ctime> → simple date & time

  • time_t stores seconds since 1970

  • tm structure breaks time into parts

  • <chrono> → modern, precise, recommended

  • Used for clocks, timers, benchmarking

You may also like...