C++ Date and Time

⏰ 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
🔹 2. Get Current Date and Time
🔹 3. Convert Time to Readable Format
Output example:
🔹 4. Using tm Structure (Break Date & Time)
🔹 5. GMT / UTC Time
✔ Returns UTC time instead of local time
🔹 6. Format Date & Time (strftime)
Common format codes:
| Code | Meaning |
|---|---|
%Y | Year |
%m | Month |
%d | Day |
%H | Hour |
%M | Minute |
%S | Second |
🔹 7. Modern CPP Date & Time (<chrono>) ✅
Include Header
Get Current Time (System Clock)
🔹 8. Convert chrono Time to time_t
🔹 9. Measure Execution Time (Very Common)
🔹 10. Sleep / Delay
✔ Pauses program for 2 seconds
🔁 <ctime> vs <chrono>
<ctime> | <chrono> |
|---|---|
| Old (C-style) | Modern C++ |
| Easy to use | More powerful |
| Less precise | High precision |
| Not type-safe | Type-safe |
📌 Summary
<ctime>→ simple date & timetime_tstores seconds since 1970tmstructure breaks time into parts<chrono>→ modern, precise, recommendedUsed for clocks, timers, benchmarking
