c++ - Boost,如何将以下字符串解析为日期/时间

标签 c++ boost-date-time

我有以下毫秒/微秒精度字符串来解析为某种提升日期时间。

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;
}

最佳答案

boost::posix_time::time_from_string 在解析格式方面非常严格。

您正在寻找一种从 std::string 创建 boost::posix_time::ptime 的不同方法。您想要将格式注入(inject) stringstream,如下所示:

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

关于c++ - Boost,如何将以下字符串解析为日期/时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26901009/

相关文章:

c++ - 如何检查验证

c++ - 异步 glTexSubImage2D 和 OGL 线程阻塞

C++ boost::posix_time::ptime 默认值

C++,自使用 boost 和 std::chrono 以来的时间?为什么 Boost 版本慢 10 倍?

c++ - 如何根据 RFC 3339 格式化 boost::date_time-object

c++ - char[] 乱七八糟的输出

c++ - Linux:/proc/self/statm 可信吗?

c++ - C++ 和 Matlab 互相关

c++ - 所有权/删除区域设置中的构面(std::locale)

c++ - 如何使用 boost::date_time 从 time_t 获取本地日期时间?