Domanda

I tried to convert std::string into boost::gregorian::date in this way:

#include <iostream>
#include "boost/date_time/gregorian/gregorian.hpp"

int main(int argc, char *argv[])
{
  std::string s_date = "1922-02-29";
  std::stringstream ss(s_date);
  boost::gregorian::date_input_facet *df = new boost::gregorian::date_input_facet("%Y-%m-%d");
  ss.imbue(std::locale(ss.getloc(), df));
  date d;
  ss>>d;
  std::cout<<d<<std::endl;
}

But unfortunately I only received "not-a-date-time". What am I doing so wrong? Is there any easier way to convert string in such a popular form to boost::gregorian:date?

È stato utile?

Soluzione

What am I doing so wrong?

You get "not-a-date-time" because that is not a valid date: 1922 wasn't a leap year, so there were only 28 days in February.

Your code works as expected for me if I change it to a valid date such as 1922-02-28 or 1924-02-29.

Is there any easier way to convert string in such a popular form to boost::gregorian:date?

boost::gregorian::date d = boost::gregorian::from_string(s_date);

Altri suggerimenti

It should be:

boost::gregorian::date d = boost::gregorian::from_undelimited_string(s_date);

Not 'from_date'

The string is required to take for form YYYYMMDD.

Or you can use:

boost::gregorian::date d = boost::gregorian::from_string(s_date);

where your string takes the form YYYY/MM/DD

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top