C++20: Query Calendar Dates and Ordinal Dates

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

This post is the sixth in my detailed journey through the chrono extension in C++20:

Query Calendar Dates

Without further ado, the following program queryCalendarDates.cpp queries a few calendar dates.

// queryCalendarDates.cpp

#include <chrono>
#include <iostream>

int main() {

    std::cout << '\n';

    using std::chrono::floor;

    using std::chrono::January;

    using std::chrono::years;
    using std::chrono::days;
    using std::chrono::hours;

    using std::chrono::year_month_day;
    using std::chrono::year_month_weekday;

    using std::chrono::sys_days;

    auto now = std::chrono::system_clock::now();              
    std::cout << "The current time is: " << now << " UTC\n";                     // (1)   
    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));                         // (2)
    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<hours>(now) - sys_days(January/1/currentYear);           // (3)
    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<hours>(now);            // (4)
    std::cout << "It is " << hBefore << " before New Year!\n";

    std::cout << '\n';
                                                            
    std::cout << "It has been " << floor<days>(hAfter) << " since New Year!\n";  // (5)
    std::cout << "It is " << floor<days>(hBefore) << " before New Year!\n";      // (6)
    
    std::cout << '\n';
    
}

With the C++20 extension, you can directly display a time point, such as now (line 1). std::chrono::floor rounds the time point down to a day std::chrono::sys_days. This value can be used to initialize the calendar type std::chrono::year_month_day. Finally, when I put the value into a std::chrono::year_month_weekday calendar type, I get the answer that this specific day is the 3rd Tuesday in October.

Of course, I can also ask for a calendar date for its components, such as the current year, month, or day (line 2).

Line 3 is the most interesting one. When I subtract from the current date, using hour resolution, the first of January of the current year, I get the number of hours since the new year. Conversely, when I subtract from the first of January of the next year (line 4) the current date, I get the hours to the new year using hour resolution. Maybe you don’t like hour resolution. Lines 5 and 6 display the values using day resolution.

Now, I want to know the weekdays of my birthdays.

Query Weekdays

Thanks to the extended chrono library, getting the weekday of a given calendar date is pretty easy.

// weekdaysOfBirthdays.cpp

#include <chrono>
#include <cstdlib>
#include <iostream>

int main() {

    std::cout << '\n';

    int y;
    int m;
    int d;

    std::cout << "Year: ";                                            // (1)                          
    std::cin >> y;
    std::cout << "Month: ";
    std::cin >> m;
    std::cout << "Day: ";
    std::cin >> d;

    std::cout << '\n';

    auto birthday = std::chrono::year(y)/std::chrono::month(m)/std::chrono::day(d);  // (2)      

    if (not birthday.ok()) {                                         // (3)                     
        std::cout << birthday << '\n';
        std::exit(EXIT_FAILURE);
    }

    std::cout << "Birthday: " << birthday << '\n';
    auto birthdayWeekday = std::chrono::year_month_weekday(birthday); // (4)  
    std::cout << "Weekday of birthday: " << birthdayWeekday.weekday() << '\n';

    auto currentDate = std::chrono::year_month_day(
        std::chrono::floor<std::chrono::days>(std::chrono::system_clock::now()));  
    auto currentYear = currentDate.year();
    
    auto age = static_cast<int>(currentDate.year()) - 
               static_cast<int>(birthday.year());                     // (5)
    std::cout << "Your age: " << age << '\n';

    std::cout << '\n';

    std::cout << "Weekdays for your next 10 birthdays" << '\n';  

    for (int i = 1, newYear = (int)currentYear; i <= 10;  ++i ) {    // (6)
        std::cout << "  Age " <<  ++age << '\n';
        auto newBirthday = std::chrono::year(++newYear)/
                           std::chrono::month(m)/std::chrono::day(d);
        std::cout << "    Birthday: " << newBirthday << '\n';
        std::cout << "    Weekday of birthday: " 
                  << std::chrono::year_month_weekday(newBirthday).weekday() << '\n';
    }

    std::cout << '\n';

}

First, the program asks you for your birthday’s year, month, and day (line 1). Based on the input, a calendar date is created (line 2) and checked for validity (line 3). Now I display the weekday of your birthday. I use the calendar date to fill in the calendar type std::chrono::year_month_weekday (line 4). To get the int representation of the calendar type year, I must convert it to int (line 5). Now I can display your age. Finally, for each of your next ten birthdays (line 6), the for loop shows the following information: your age, the calendar date, and the weekday. I only have to increment the age and newYear variables.

Here is a run of the program with my birthday.

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

Be part of my mentoring programs:

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (starts March 2024)
  • Do you want to stay informed: Subscribe.

     

    Calculating Ordinal Dates

    As a last example of the new calendar facility, I want to present the online resource Examples and Recipes from Howard Hinnant, which has about 40 examples of the new chrono functionality. Presumably, the chrono extension in C++20 is not easy to get; therefore, it’s essential to have so many examples. You should use these examples as a starting point for further experiments and sharpen your understanding. You can also add your recipes.

    To get an idea of Examples and Recipes, I want to present a slightly modified program by Roland Bock that calculates ordinal dates.

    An ordinal date consists of a year and a day of year (1st of January being day 1, 31st of December being day 365 or day 366). The year can be obtained directly from year_month_day. And calculating the day is wonderfully easy. In the code below, we make us of the fact that year_month_day can deal with invalid dates like the 0th of January:” (Roland Bock)

    I added the necessary headers to Roland’s program.

    // ordinalDate.cpp
    
    #include "date.h"
    #include <iomanip>
    #include <iostream>
    
    int main()
    {
       using namespace date;
       
       const auto time = std::chrono::system_clock::now();
       const auto daypoint = floor<days>(time);                    // (1) 
       const auto ymd = year_month_day{daypoint};         
       
       // calculating the year and the day of the year
       const auto year = ymd.year();
       const auto year_day = daypoint - sys_days{year/January/0}; // (2) 
                                                                  // (3)
       std::cout << year << '-' << std::setfill('0') << std::setw(3) << year_day.count() << std::endl;
       
       // inverse calculation and check
       assert(ymd == year_month_day{sys_days{year/January/0} + year_day});
    }
    

    I want to add a few remarks to the program. Line (1) truncates the current time point. The value is used in the following line to initialize a calendar date. Line (2) calculates the time duration between the two time points. Both time points have the resolution day. Finally, year_day.count() inline (3) returns the time duration in days.

    What’s Next?

    A key component in my posts to the extended chrono library in C++20 is still missing: time zones.

    Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, moon, Philipp Lenk, Hobsbawm, Charles-Jianye Chen, and Keith Jeffery.

    Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Seminars

    I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

    Standard Seminars (English/German)

    Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

    • C++ – The Core Language
    • C++ – The Standard Library
    • C++ – Compact
    • C++11 and C++14
    • Concurrency with Modern C++
    • Design Pattern and Architectural Pattern with C++
    • Embedded Programming with Modern C++
    • Generic Programming (Templates) with C++
    • Clean Code with Modern C++
    • C++20

    Online Seminars (German)

    Contact Me

    Modernes C++ Mentoring,