Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C

Parse date time string with spirit

2.00/5 (5 votes)
19 Mar 2008CPOL 2   128  
A sample show how to parse date with boost spirit framework

Introduction

This article include a sample show how to use boost spirit framework parse a date time string like "1999-01-20T00:01:22".

Background

The XML schema define the date time format like this "2000-01-30T00:10:20+1".

Using the code

First create your parser

struct myparser: public grammar<myparser>
{
  template <typename ScannerT>
  struct definition
  {
    definition(myparser const& self)
    {
      first = int_p[assign(self.date_.year_)] >> "-" >> int_p[assign(self.date_.month_)] 
      >> "-" >> int_p[assign(self.date_.day_)] >> "T" >> int_p[assign(self.date_.hour_)] 
      >> ":" >> int_p[assign(self.date_.minute_)] >> ":" >> int_p[assign(self.date_.second_)] ;
    }
    rule<ScannerT> first;
    rule<ScannerT> const&
    start() const { return first; }
  };
  myparser(date& d):date_(d){};
  date& date_;
};        

Then invoke the parser:

bool parse_date(char const* str, date& d)
{
  myparser p(d);
  return parse(str, p).full;
}      

Points of Interest

This parser can be improved to support more flexible format

History

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)