Boost logo

Boost Users :

From: Jason Dolan (jason_at_[hidden])
Date: 2006-06-27 10:18:12


Jeff Garland wrote:
> Jason Dolan wrote:
>> I'm looking to take a string and convert it to a date. The only problem
>> is the string can be one of many patterns. i.e. ("%Y%m%d", "%Y-%m-%d",
>> "%d/%m/%Y", etc...). It is also possible that the given string will
>> fail all pattern matches, and thus return false.
>
> And there's nothing to indicate which pattern it might be?
Nope. I'm basically allowing the user to input a date and time *almost*
anyway they want. What I want to do is test that string against my list
of patterns(i.e. known ways to write a date and time) to try and parse
the date.

What I'm doing right now is:

bool SetDate(string &strDate)
{
        m_vecFormats[0] = "%Y%m%d";
        m_vecFormats[1] = "%Y-%m-%d";
        m_vecFormats[2] = "%d/%m/%Y";
        m_vecFormats[3] = "%d/%m/%Y %H:M%";
        ...
        ...
        ...
        
        for(int iter=0; iter < m_vecFormats.size() && bValidDate == false; iter++)
        {
                cerr << "Trying format: " << m_vecFormats[iter];
                if(SetDate(strDate, m_vecFormats[iter]))
                {
                        cerr << "\tWORKED!!" << endl;
                        bValidDate = true;
                }
                else
                        cerr << "\tFAILED!!" << endl;
        }
}

bool SetDate(string &strDate, string &strFormat)
{
        bool bValidDate = false;
        time_input_facet *f = new time_input_facet();
        f->format(strFormat.c_str());
        ptime d(not_a_date_time);
        stringstream ss;
        ss.imbue(locale(ss.getloc(), f));
        ss << strDate;
        ss >> d;
        
        if(!d.is_not_a_date_time())
        {
                bValidDate = true;
        }
        
        return bValidDate;
}

But I'm not sure if this is the right way to go about it. Further, what
  happens if they just put in a time (it would make sense to assume it
is the current date), Can this handle a two digit year? I wouldn't think
so...

Besides that, each time the second SetDate function is called (which
will be once for each format for the worst case), I have to create a
time_input_facet object, a stringstream object and a pdate object. It
would be nice to have a function like this use less resources since it's
called so much.


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