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


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;”?.

Leave a Reply

Your email address will not be published. Required fields are marked *