...

/

Query Calendar Dates and Weekdays

Query Calendar Dates and Weekdays

Learn how to use the extended chrono library to query calendar dates and weekdays.

We'll cover the following...

The extended chrono library makes it quite easy to ask for the time duration between calendar dates.

Query calendar dates

Without further ado. The following program queries a few calendar dates.

Press + to interact
#include "date.h"
#include <iostream>
int main() {
using namespace date;
std::cout << '\n';
auto now = std::chrono::system_clock::now();
std::cout << "The current time is: " << now << " UTC\n";
std::cout << "The current date is: " << floor<days>(now) << '\n';
std::cout << "The current date is: " << year_month_day{floor<days>(now)}
<< '\n';
std::cout << "The current date is: " << year_month_weekday{floor<days>(now)}
<< '\n';
std::cout << '\n';
auto currentDate = year_month_day(floor<days>(now));
auto currentYear = currentDate.year();
std::cout << "The current year is " << currentYear << '\n';
auto currentMonth = currentDate.month();
std::cout << "The current month is " << currentMonth << '\n';
auto currentDay = currentDate.day();
std::cout << "The current day is " << currentDay << '\n';
std::cout << '\n';
auto hAfter = floor<std::chrono::hours>(now) - sys_days(January/1/currentYear);
std::cout << "It has been " << hAfter << " since New Year!\n";
auto nextYear = currentDate.year() + years(1);
auto nextNewYear = sys_days(January/1/nextYear);
auto hBefore = sys_days(January/1/nextYear) - floor<std::chrono::hours>(now);
std::cout << "It is " << hBefore << " before New Year!\n";
std::cout << '\n';
std::cout << "It has been " << floor<days>(hAfter) << " since New Year!\n";
std::cout << "It is " << floor<days>(hBefore) << " before New Year!\n";
std::cout << '\n';
}

With the C++20 extension, you can directly display a time ...