I use std::get_time
to parse dates from text. In most cases it is sufficient, but when reading dates with no separators (e.g. 31122021
, with format "%d%m%Y"
) I always get a failure. I use this because I saw it described as an equivalent to python's strptime
(https://stackoverflow.com/a/33542189/15061775) which does manage this use case (How to parse an 8 digit number as a date?).
Here is my code (tested MRE) :
#include <cassert>
#include <ctime>
#include <iomanip>
#include <sstream>
#define MAKEDATE(d,m,y) (((y&0xFFFF)<<16)|((m&0xFF)<<8)|(d&0xFF))
uint32_t Get_Date(const char *str_date, const char **out, const char *format)
{
std::tm dt = {};
std::istringstream stream(str_date);
stream >> std::get_time(&dt, format);
if (stream.fail())
{
if (out) *out = NULL;
return MAKEDATE(1, 1, 1900);
}
else
{
if (out) *out = str_date + (int)stream.tellg();
return MAKEDATE(dt.tm_mday, 1 + dt.tm_mon, 1900 + dt.tm_year);
}
}
int main(void)
{
assert(Get_Date("31122021", NULL, "%d%m%Y") == MAKEDATE(31, 12, 2021));
}
I compile it using VS2017's default compiler settings using MFC and CLI, with MSVC 19.10.25027.
Did I make a mistake? Is there another flag or set of flags I could use? Is there another, simple parsing method?