mardi 2 août 2016

conversion between std::string and std::time_t

I want to store a string containing a date to std::time_t.

And then later convert this std::time_t value back to string.

The two string should be the same.

Here is the code, but the second string is not the same as the first one.

#include <iostream>
#include <ctime>
#include <string>
#include <sstream>
#include <iomanip>

int main()
{
    // convert string to time_t
    std::string date_str = "2014-01-25";
    std::tm tm;
    std::istringstream str_stream(date_str);
    str_stream >> std::get_time(&tm, "%Y-%m-%d");
    std::time_t time = std::mktime(&tm);
    std::cout << time << std::endl;

    // convert time_t back to string, it should be 2014-01-25
    std::stringstream stream;
    // both localtime and gmtime won't work
    stream << std::put_time(std::localtime(&time), "%F");
    std::cout << stream.str() << std::endl;
}

Aucun commentaire:

Enregistrer un commentaire