Click here to Skip to main content
15,881,757 members
Articles / Programming Languages / C

Parse date time string with spirit

Rate me:
Please Sign up or sign in to vote.
2.00/5 (5 votes)
19 Mar 2008CPOL 28.2K   128   7  
A sample show how to parse date with boost spirit framework
// testspirit.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <boost/spirit/core.hpp>
#include <boost/spirit/actor/push_back_actor.hpp>
#include <iostream>
#include <vector>
#include <string>

using namespace std;
using namespace boost::spirit;

struct date
{
  unsigned int year_;
  unsigned int month_;
  unsigned int day_;
  unsigned int hour_;
  unsigned int minute_;
  unsigned int second_;
};

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_;
};

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

void test_parse_1() {
    cout << "Give me a date like 1900-01-02T00:01:02.\n";
    cout << "Type [q or Q] to quit\n\n";

    string str;
    while (getline(cin, str))
    {
        if (str.empty() || str[0] == 'q' || str[0] == 'Q')
            break;

        date d;
        if (parse_date(str.c_str(), d))
        {
            cout << "-------------------------\n";
            cout << "Parsing succeeded\n";
            cout << str << " Parses OK: " << endl;

            cout << d.year_ << "-" << d.month_ << "-" << d.day_ 
              << "T" << d.hour_ << ":" << d.minute_ << ":" << d.second_ << "\n";

            cout << "-------------------------\n";
        }
        else
        {
            cout << "-------------------------\n";
            cout << "Parsing failed\n";
            cout << "-------------------------\n";
        }
    }

    cout << "Bye... :-) \n\n";

}

int _tmain(int argc, _TCHAR* argv[])
{
  test_parse_1();
	return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Software Developer (Senior)
China China
Programmer live in china.
Interesting with knowledge management.

My home page: http://herosys.net

Comments and Discussions