User Tools

Site Tools


C++20 chrono calendar functions

calendar.cpp
#include <iostream>
#include <chrono>
#include <sstream>
#include <iostream>
#include <iomanip>
 
//using namespace std::chrono;
 
void print_tp(std::chrono::system_clock::time_point tp) {
    std::time_t time = std::chrono::system_clock::to_time_t(tp);
    std::stringstream ss;
    ss << std::put_time(std::localtime(&time), "%Y-%m-%d %X");
    std::cout << ss.str() << std::endl;
}
 
int main() {
    using namespace std::chrono;
 
    //auto ywdl {Monday[2]/2/2021};
    //auto ywdl {year(2021)/February/1};
 
    //auto mwdl {March/Friday[last]};
    //auto ywdl {year(2021)/mwdl};
 
    //auto ywdl1 {Monday[1]/1/2021};
    auto ywdl1 {year(2021)/1/Monday[1]};
    auto ywdl2 {year(2021)/3/Sunday[last]};
 
    //auto tp = floor<days>(system_clock::now());
    //auto tp = year_month_day{floor<days>(system_clock::now())};
 
    auto tp1 = sys_days(ywdl1) - days(7); //24h * 7;
    auto tp2 = sys_days(ywdl2) + days(7); //24h * 7;
 
    //auto ymd = year_month_day(tp1);
    //tp1 = sys_days(ymd);
 
    print_tp(tp1);
    print_tp(tp2);
}

Out

2020-12-28 02:00:00
2021-04-04 02:00:00