C ++ parsing YYMMDD ISO 8601 date string with std :: get_time gives unexpected result?

I am trying to parse a date formatted as YYMMDD. As a test, I tried the following code:

#include <iostream>
#include <sstream>
#include <locale>
#include <iomanip>

int main(){
    std::tm t = {};
    std::istringstream ss("191203");
    ss >> std::get_time(&t, "%y%m%d");
    if (ss.fail()){ 
        std::cout << "Parse failed\n";
    } else {
        std::cout << std::put_time(&t, "%c") << '\n';
    }
}

Tested with Coliru, GCC 6.1 (C ++ 17), output:

Sun Mar  0 00:00:00 1912

I expected:

Mon Dec 3 00:00:00 2019

Is there something wrong with the format string?

+4
source share
2 answers

You can use the Howard Hinnant free, open source date and time library :

#include "date.h"
#include <iostream>
#include <sstream>

int
main()
{
    date::sys_days t;
    std::istringstream ss("191203");
    ss >> date::parse("%y%m%d", t);
    if (ss.fail())
        std::cout << "Parse failed\n";
    else
        std::cout << date::format("%c", t) << '\n';
}

It runs on gcc 6.1: http://melpon.org/wandbox/permlink/gy3wpMXeCoxk9Ykj (as well as other platforms). Except for the correct exit:

Tue Dec  3 00:00:00 2019
+1

. Y2K. tm_year in std::tm 1900 . , , , , 1900 . , date, POSIX :

date -d'27 JUN 69' +%Y
1969
date -d'27 JUN 68' +%Y
2068
0

Source: https://habr.com/ru/post/1672798/


All Articles