Search code examples
datetimeboostmilliseconds

Parsing microseconds with boost


I am looking for the boost::posix_time::time_input_facet that will let me parse milliseconds. It does not seem to be the same as the one for formatting microseconds which is "%f"

So if I have 2011-12-11 08:29:53.123000, I would like to have the right formatting to parse it, something like that "%Y-%m-%d %H:%M:%S".


Solution

  • If you have a date/time string you can convert that into a ptime object like this:

    using boost::posix_time;
    ptime t = time_from_string(datetimeString);
    

    Having this you can easily get hold of the time_duration which holds the fractional seconds.

    time_duration td = t.time_of_day();
    long fs = td.fractional_seconds();
    

    You can also get the total milliseconds or microseconds like this:

    long ms = td.total_milliseconds();
    long us = td.total_microseconds();
    

    More information about what can be done in the documentation.

    UPDATE

    If the input format might be a different one, so you want to use the time_input_facet you can check the time_facet.hpp for appropriate format. Here is what you probably want to select from:

      static const char_type fractional_seconds_format[3];               // f                                                                                                                                 
      static const char_type fractional_seconds_or_none_format[3];       // F                                                                                                                                 
      static const char_type seconds_with_fractional_seconds_format[3];  // s
    

    UPDATE2

    In time_facet.hpp (Boost 1.45) I see the following when parsing:

    case 'f':
    {
        // check for decimal, check special_values if missing                                                                                                                                       
        if(*sitr == '.') {
            ++sitr;
            parse_frac_type(sitr, stream_end, frac);
            ...
    

    I don't see why this would require anything but a dot between the seconds and the fractional seconds. Maybe you use another version of Boost?