Search code examples
c++visual-studioc++-chrono

How to to print current time and assign it to a year_month_day variable with C++ chrono


In Visual studio 2022, C++20, I want to print the current time with year, month and day.

I tried to do it with:

cout<<today << endl

But I got this error:

Error C2679 binary "<<": No operator found to accept right operand of type "std:: initializer_list<std:: Chrono:: time_point<std:: Chrono:: systemi_clock, std:: Chrono:: days>>" (or no acceptable conversion)

My code:

#include <time.h>
#include <iostream>
#include <format>
#include <string>
#include <ratio>
#include <chrono>
#include <iomanip>

using namespace std;
using namespace chrono;

int main()
{
    auto today = { floor<days>(system_clock::now()) };
    cout << today << endl;
    system("pause");
}

if I try to assign today to year_month_day,it also does not work:

year_month_day ymd = today;
cout << ymd.year() << endl;

With this error:

Error C2440: "Initialize": Unable to convert from "std:: initializer_list<std:: Chrono:: time_point<std:: Chrono:: systemi_clock, std:: Chrono:: days>>" to "std:: Chrono:: year_month_day"

How should I do it ?


Solution

  • The problem:

    In this line:

    auto today = { floor<days>(system_clock::now()) };
    

    The curly braces ({ ... }) around the value used to initlize today, cause auto to deduce the type to std::initializer_list<...>.

    std::cout does not support it out-of-the-box.

    The actual type that you need today to be is std::chrono::time_point<...>.

    Solution:

    You can solve it in one of two ways:

    1. Remove the curly braces so that auto will deduce the proper type:

      auto today = floor<days>(system_clock::now());
      
    2. Remove the = sign, which will make it conform a uniform initaialization:

      auto today{ floor<days>(system_clock::now()) };
      

    After initializing today like this, you will be able to both use std::cout to print it, and assign it to year_month_day ymd.

    Complete example (with 2nd solution):

    #include <iostream>
    #include <chrono>
    
    int main()
    {
        auto today{ floor<std::chrono::days>(std::chrono::system_clock::now()) };
        std::cout << today << std::endl;
    
        std::chrono::year_month_day ymd = today;
        std::cout << ymd.year() << std::endl;
    }
    

    Possible output:

    2024-06-16
    2024
    

    Live demo

    A side note:
    Better to avoid using namespace std;. See: What's the problem with "using namespace std;"?.