Parsing a date / time in C ++ (any format string in Epoch)

I am writing a C ++ application that should parse a date / time string and output an era time. But the date / time string format can be more than one (actually say 25 formats), for example

    "EEE, dd MMM yyyy HH:mm:ss '('ZZZ')'",
    "EEE, dd MMM yyyy HH:mm:ss '\"'ZZZ'\"'",
    "EEE, dd MMM yyyy hh:mm:ss z",
    "EEE, dd MMM yyyy HH:mm Z",
    "EEE, dd MMM yyyy HH:mm:ss",
    "EEE, MMM dd, yyyy 'at' HH:mm:ss z",
    "EEE M/dd/yyyy hh:mm:ss a",
    "EEE MMM dd HH:mm:ss z yyyy",
    "EEE MMM dd hh:mm:ss yyyy",
    "EEEE, MMMM dd, yyyy hh:mm:ss a",
    "EEEE, MMMM dd, yyyy HH:mm a",
    "EEEE, MMMM dd, yyyy HH:mm",
    "MMM dd, yyyy hh:mm:ss a",
    "dd MMM yyyy hh:mm:ss z",
    "dd-MMM-yyyy HH:mm:ss z",
    "dd MMM yy HH:mm:ss",
    "MM/dd/yyyy  hh:mm a  (EEEE)",
    "MM/dd/yyyy hh:mm a (EEEE)",
    "MM/dd/yyyy hh:mm:ss",
    "MM/dd/yyyy hh:mm a Z",
    "MM/dd/yyyy hh:mma Z",
    "MM/dd/yyyy hh:mma",
    "MM/dd/yyyy hh:mm a",
    "MM/dd/yyyy hh:mm Z",
    "MM/dd/yy hh:mm a Z",
    "MM/dd/yy hh:mma Z",
    "MM/dd/yy HH:mm a",
    "MM/dd/yy HH:mm Z",
    "MM/dd/yyyy",   
    "yyyy-MM-dd HH:mm:ss",
    "yyyyMMddhhmmss",
    "yyyyMMddhhmm",
    "yyyyMMdd"

Now I need to take a string, find out if it belongs to which of these formats, and then get the time in the era.

Can you suggest a way to do this. Sample code will be really helpful. I do Boost libraries. Let me know if this can be achieved using date / time parsing modules.

Thanks in advance, AJ

+5
source share
1 answer

, ptime , not_a_date_time.:

, :

#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
using boost::posix_time::time_input_facet;
using std::locale;
const locale inputs[] = {
    locale(locale::classic(), new time_input_facet("%m/%d/%Y")),
    locale(locale::classic(), new time_input_facet("%Y-%m-%d %H:%M:%S")),
    locale(locale::classic(), new time_input_facet("%Y%m%d%H%M%S")),
    locale(locale::classic(), new time_input_facet("%Y%m%d%H%M")),
    locale(locale::classic(), new time_input_facet("%Y%m%d")) };
const size_t formats = sizeof(inputs)/sizeof(inputs[0]);

time_t ptime_to_time_t(boost::posix_time::ptime t)
{
       static boost::posix_time::ptime epoch(boost::gregorian::date(1970,1,1));
       return (t-epoch).ticks() / boost::posix_time::time_duration::ticks_per_second();
}
int main()
{
       std::string msg = "2010-08-04 08:34:12";

       for(size_t i=0; i<formats; ++i)
       {
           std::istringstream ss(msg);
           ss.imbue(inputs[i]);
           boost::posix_time::ptime this_time;
           ss >> this_time;

           if(this_time != boost::posix_time::not_a_date_time)
               std::cout << this_time << " or " << ptime_to_time_t(this_time) << std::endl;
       }
}
+13

All Articles