Boost logo

Boost Users :

Subject: [Boost-users] [date_time] howto determine date format?
From: Markus Werle (numerical.simulation_at_[hidden])
Date: 2010-02-24 09:08:40


Hi!

With the code below I try to automagically determine the date
format found in input files. I'd expect the code below to find the
date format "%d.%m.%Y" for "05.02.2008", but I got surprised by
obtaining "%m/%d/%Y". A major pain it is with those dates.
Whether my shallow knowledge of locales and imbue
or boost::date_time (from boost-1.37.0) is to be blamed is
beyond my horizon.

I feel like date accepts '.' where I said "expect '/'", so I think
this should be changed. I may be wrong.

Could you please shed some light on the issue?

Thanks, Markus

#include <boost/assign/list_of.hpp>

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>

#include <string>
#include <list>

inline std::string determine_date_format(std::string const & s)
{
    using namespace boost::assign;
    using namespace boost::gregorian;

    std::list<std::string> possible_formats = // TODO: add others here!
        list_of ("%Y-%m-%d")("%Y/%m/%d")("%m/%d/%Y")("%d.%m.%Y");

    bool inform_user = false;

    BOOST_FOREACH(std::string const & format, possible_formats)
    {
        if (inform_user)
        {
            std::cout << "Trying format '" << format << "' ..." << std::endl;
        }

        try
        {
            date_input_facet * input_facet =
                new date_input_facet(format.c_str());
            std::istringstream iss(s);
            iss.imbue(std::locale(iss.getloc(), input_facet));
            date d(not_a_date_time);
            
            iss >> d;
            if (!iss.fail() && (!d.is_not_a_date()))
            {
                return format;
            }

            std::cout << "WARNING: date format '" << format
                      << "' does not match '" << s << "'." << std::endl;
            inform_user = true;
        }
        catch(...)
        {
        }
    }

    std::cout << "WARNING: date format not recognized. "
              << "Please reconfigure your measurement equipment "
              << "to ISO standard output!"
              << std::endl;
    
    return "";
}

int main()
{
    std::string the_date = "05.02.2008";
    std::string format = determine_date_format(the_date);
    std::cout << the_date << " has date-time-format "
              << format << 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