get_time parsing error for two digits year

Viewed 127

std::get_time is behaving in the same way when the format includes '%y' or '%Y', in both cases it tries to read a four digit year. Am I doing something wrong or is it a bug ?

Example code:

#include <iostream>
#include <iomanip>

void testDate(const char *format,const char *date)
{
    std::istringstream ds(date);

    std::tm tm = {};
    ds >> std::get_time(&tm,format);
    std::cout<<date<<" parsed using "<<format<<" -> Year: "<<tm.tm_year+1900<<" Month: "<<tm.tm_mon<<" Day: "<<tm.tm_mday<<std::endl;
}

int main()
{
    testDate("%y%m%d","101112");
    testDate("%Y%m%d","101112");
    testDate("%y%m%d","20101112");
    testDate("%Y%m%d","20101112");
    
    
    return 0;
}

Output:

101112 parsed using %y%m%d -> Year: 1011 Month: 11 Day: 0
101112 parsed using %Y%m%d -> Year: 1011 Month: 11 Day: 0
20101112 parsed using %y%m%d -> Year: 2010 Month: 10 Day: 12
20101112 parsed using %Y%m%d -> Year: 2010 Month: 10 Day: 12

Tested with:

g++ (SUSE Linux) 11.2.1 20210816 [revision 056e324ce46a7924b5cf10f61010cf9dd2ca10e9]

clang++ version 12.0.1

1 Answers

Found after testing

  • %y - Enter only two digits
  • %Y - Enter only four digits

If you use 4 digits when using %y, then 4 digits will be output directly, if it is 2 digits, it is consistent with the document

The Month

The Month, From the std::tm

tm_mon : months since January – [0, 11]

so it print out 11 represents December. You can use below code to print out the date.

    std::cout << std::put_time(&tm, "%c") << std::endl;
Related