|
Boost Users : |
From: Alexandre Gacon (alexandre.gacon_at_[hidden])
Date: 2006-03-22 03:02:58
Why don't you use the input/output facet with a stream to define the format
you want ?
For example I was able to define my own time format as simply as this:
pt::time_input_facet* pInputFacet = new pt::time_input_facet();
pInputFacet->time_duration_format( "%H:%M" );
std::locale loc( std::locale::classic(), pInputFacet );
ss.imbue( loc );
You can do the same with the boost::gregorian::date. Check the documentation
(at least if you use the 1.33.1 version of boost).
I hope it will help you.
Alexandre Gacon
-----Message d'origine-----
De : boost-users-bounces_at_[hidden]
[mailto:boost-users-bounces_at_[hidden]] De la part de Andrew Holden
Envoyé : mardi 21 mars 2006 23:18
À : boost-users_at_[hidden]
Objet : Re: [Boost-users] [date_time] How to create a date from
stringwithspecific format?
> -----Original Message-----
> From: Christian Henning [mailto:chhenning_at_[hidden]]
> Sent: Tuesday, March 21, 2006 4:23 PM
> To: boost-users_at_[hidden]
> Subject: Re: [Boost-users] [date_time] How to create a date from
string
> withspecific format?
>
> Hi Dean, thanks for the answer.
>
> Since, I know the format of the date strings I could also use
> boost::regex for the general format and then feeding a date object
> with the values. If I get an exception during the date object
> contruction I know that the user provided me with garbage.
>
>
> Any thoughts on that?
>
> Thanks again,
> Christian
Have you considered using Regex's submatches? A slightly modified example
follows.
// date format: mm-dd-yyyy
boost::regex oDateReg( "(\\d{2})-(\\d{2})-(\\d{4})" );
std::string strDate( "11-33-1997" );
boost::smatch dateMatch;
if( boost::regex_match( strDate
, dateMatch
, oDateReg ))
{
try
{
std::string strMonth = dateMatch[1];
std::string strDay = dateMatch[2];
std::string strYear = dateMatch[3];
unsigned int nYear = boost::lexical_cast<unsigned
int>(strYear);
unsigned int nMonth = boost::lexical_cast<unsigned
int>(strMonth);
unsigned int nDay = boost::lexical_cast<unsigned
int>(strDay);
date d( nYear, nMonth, nDay );
date::ymd_type ymd = d.year_month_day();
}
catch( std::out_of_range oEx )
{
std::cout << "Error: " << oEx.what() << std::endl;
}
}
There are two advantages to this. First, you no longer need to count
characters when extracting the date components. Second, you have a little
more freedom in defining your date format. For example, you could use the
following definition for oDateReg to also accept single-digit months and/or
days:
boost::regex oDateReg( "(\\d{1,2})-(\\d{1,2})-(\\d{4})" );
Andrew Holden
_______________________________________________
Boost-users mailing list
Boost-users_at_[hidden]
http://lists.boost.org/mailman/listinfo.cgi/boost-users
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