Unnecessary use of wide strings
In your example, there is no need to use wide strings for date_time_format
and ss
. Just use std::string
and std::istringstream
and drop the L
prefix for the string literals.
Missing std::
You are using localtime()
without std::
in front. If you include the C++ versions of the C header files, then there is no guarantee that the C functions will be available in the global namespace.
Use '\n'
instead of std::endl
Prefer using '\n'
instead of std::endl
; the latter is equivalent to the former, but also forces the output to be flushed, which is usually not necessary and has a negative impact on performance.
Missing error checking
If you are trying to parse strings you don't have full control over, the parsing might fail. You should check that ss
is still in a good state after trying to parse the date.
Consider using C++20
If you are stuck with C++17 or earlier, then the code you wrote is the only standards compliant way to parse time. However, the situation has improved in C++20 with the introduction of std::chrono::parse()
and other calendar features. If you are lucky and your compiler and standard library support it already, you can write:
#include <iostream>
#include <sstream>
#include <chrono>
int main()
{
std::string date_time_format = "%m/%d/%Y";
std::istringstream ss{ "4/28/2022" };
std::chrono::year_month_day date;
ss >> std::chrono::parse(date_time_format, date);
if (!ss) {
/* failed to parse date */
...
}
std::cout << "Year: " << date.year() << '\n';
std::cout << "Month: " << date.month() << '\n';
std::cout << "Day: " << date.day() << '\n';
}