← C++ from Scratch Lesson 46 of 62 · 10 XP

Date and time: <chrono>

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

<chrono> is for time and dates. C++20 added a calendar:

#include <chrono>
using namespace std::chrono;

year_month_day d{year{2026}, month{11}, day{5}};
d.ok();                                  // true — such a date exists (but 2026-02-30 doesn't)
sys_days t = d;                          // days since 1970-01-01 — handy for calculations
weekday wd{t};                           // the day of the week
wd.c_encoding();                         // 0 = Sunday, 1 = Monday, … 6 = Saturday
(sys_days{year{2027}/1/1} - t).count();  // how many days until New Year's Day
year_month_day later{t + days{30}};      // the date in 30 days

To measure how long code takes, there are clocks: auto t0 = steady_clock::now(); … duration_cast<milliseconds>(steady_clock::now() - t0).count().

Do date calculations in programs with sys_days — that way you won't get the length of months or leap years wrong.

Task. Read a date year month day. If it doesn't exist, print invalid. Otherwise print the day of the week in English (Monday … Sunday), how many days there are until 1 January of the next year, and the date in 100 days in the format YYYY-MM-DD.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.