5

ある種のブースト日時に解析する次のミリ/マイクロ秒の精度の文字列があります。

std::string cell ="20091201 00:00:04.437";

ファセットに関するドキュメントを見てきました。このようなもの

date_input_facet* f = new date_input_facet();
f->format("%Y%m%d %F *");

しかし、私はそれらを使用する方法がわかりません。

StackOverflow から収集したコードを使用してこのプログラムを試しましたが、ミリ秒を表示できません。

#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <map>

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

namespace bt = boost::posix_time;

const std::locale formats[] =
{
    std::locale(std::locale::classic(),new bt::time_input_facet("%Y%m%d %H:%M:%S.f")),
    std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
    std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")),
    std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")),
    std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d"))
};

const size_t formats_n = sizeof(formats) / sizeof(formats[0]);

std::time_t pt_to_time_t(const bt::ptime& pt)
{
    bt::ptime timet_start(boost::gregorian::date(1970,1,1));
    bt::time_duration diff = pt - timet_start;

    return diff.ticks()/bt::time_duration::rep_type::ticks_per_second;

}

void seconds_from_epoch(const std::string& s)
{
    bt::ptime pt;
    for(size_t i = 0; i < formats_n; ++i)
    {
        std::istringstream is(s);
        is.imbue(formats[i]);
        is >> pt;
        if(pt != bt::ptime()) break;
    }

    bt::time_duration td = pt.time_of_day();
    long fs = td.fractional_seconds();

    std::cout << " ptime is " << pt << '\n';
    std::cout << " seconds from epoch are " << pt_to_time_t(pt) << " " << fs << '\n';
}

int main(int, char *argv[])
{
    std::string cell ="20091201 00:00:04.437";

    seconds_from_epoch(cell);

    int enterAnumber;
    std::

    cin >> enterAnumber;
}
4

1 に答える 1

8

boost::posix_time::time_from_string形式の解析に関しては非常に厳格です。

boost::posix_time::ptimeからを作成する別の方法を探していますstd::stringstringstream次のように、 a に次の形式を吹き込みます。

const std::string cell = "20091201 00:00:04.437";
const std::locale loc = std::locale(std::locale::classic(), new boost::posix_time::time_input_facet("%Y%m%d %H:%M:%S%f"));
std::istringstream is(cell);
is.imbue(loc);

boost::posix_time::ptime t;
is >> t;

それで

std::cout << t << std::endl;

与える

2009-Dec-01 00:00:04.437000
于 2014-11-13T04:18:23.197 に答える