Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::chrono::from_stream correct usage

I am thinking about usage of function std::chrono::from_stream (std::chrono::year_month_day) to get std::chrono::year_month_day object from const std::string& like 2018-12-09T00:00:00.

In cppreference is no example of usage std::chrono::from_stream. So I thought, that it could be used in the same way like std::get_time.

But there is a catch. std::chrono::year_month_day has really wierd parameters (personal opinion)

(std::basic_istream<CharT, Traits>& is, const CharT* fmt, std::chrono::year_month_day& ymd, std::basic_string<CharT, Traits, Alloc>* abbrev = nullptr, std::chrono::minutes* offset = nullptr)

and return for unknown reason std::basic_istream, so I realized that I really don't know, how to correctly use it.

Does anyone knows please? Thanks.

like image 205
Přemysl Šťastný Avatar asked Oct 21 '25 04:10

Přemysl Šťastný


1 Answers

It's not so weird.

const std::string in = "2018-12-09T00:00:00";
std::stringstream ss(in);

std::chrono::year_month_day ymd;

if (std::chrono::from_stream(ss, "%FT%T", ymd))
{
    std::cout << "Date: " << ymd << '\n';
}

(Sadly we cannot demo this yet, as libstd++ doesn't implement P0355, and libc++'s nascent support is insufficient.)

Note that this only provides the year/month/day, so the time must be discarded.

You may wish to consider some of the other from_stream overloads (like maybe this one).

like image 194
Lightness Races in Orbit Avatar answered Oct 22 '25 18:10

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!