Boost logo

Boost Users :

From: Jeff Garland (jeff_at_[hidden])
Date: 2005-10-26 08:17:10


On Wed, 26 Oct 2005 09:26:43 +0200, Roman Morokutti wrote
> Is it possible to parse a date out from a string
> like this? The example below is from a java program.
>
> private static final String PLANSTART_PATTERN = "dd.MM.yyyy HH:mm";
>

...snip code from another language which shouldn't be posted here ;-)

Yes, trivially. I've shown 2 functions below. One that uses exceptions for
error handling and one that just ignores errors. The exception based program
prints the error and then returns not-a-date-time. parse_jdate2, on the other
hand, just returns not-a-date-time on a parse failure. You'll need 1.33 for
this code to work.

Jeff

--------------

Output from the program below is:

2005-Dec-01 10:30:00
Day of month value is out of range 1..31
not-a-date-time
2005-Dec-01 10:30:00
not-a-date-time

#include "boost/date_time/posix_time/posix_time.hpp"
#include <sstream>

using namespace boost::gregorian;
using namespace boost::posix_time;

ptime
parse_jdate1(const std::string& s)
{

  ptime t;
  try {
    std::stringstream ss(s.c_str());
    time_input_facet* timefacet = new time_input_facet("%d.%m.%Y %H:%M");
    ss.imbue(std::locale(std::locale::classic(), timefacet));
    ss.exceptions(std::ios_base::failbit); // turn on exceptions
    ss >> t;
  }
  catch(std::exception& e) {
    std::cout << e.what() << std::endl;
  }
  return t;

}

ptime
parse_jdate2(const std::string& s)
{

  ptime t;
  std::stringstream ss(s.c_str());
  time_input_facet* timefacet = new time_input_facet("%d.%m.%Y %H:%M");
  ss.imbue(std::locale(std::locale::classic(), timefacet));
  ss >> t;
  return t;

}

int
main()
{

  std::cout << parse_jdate1("01.12.2005 10:30") << std::endl;
  std::cout << parse_jdate1("garbage_string") << std::endl;
  std::cout << parse_jdate2("01.12.2005 10:30") << std::endl;
  std::cout << parse_jdate2("garbage_string") << std::endl;
  return 0;
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net