我正在寻找一个样本,将日期转换为来自任意时期的日期(日期小于标准1970年)
我发现以下非常好的样本(来自答案): How to parse date/time from string?
#define BOOST_ALL_NO_LIB
#include <iostream>
#include <sstream>
#include <locale>
#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")),
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;
}
std::cout << " ptime is " << pt << '\n';
std::cout << " seconds from epoch are " << pt_to_time_t(pt) << '\n';
}
int main()
{
seconds_from_epoch("2004-03-21 12:45:33");
seconds_from_epoch("2004/03/21 12:45:33");
seconds_from_epoch("23.09.2004 04:12:21");
seconds_from_epoch("2003-02-11");
}
问题是,显然在VC ++ 2013 / Boost 1.59中不起作用,所有日期都打印为“非日期”(循环中的条件来自“if(pt!= bt :: ptime())”从来没有真实过。)
在调试器中为“is&gt;&gt; pt”挖掘一下,似乎MSVC STL在全局表中查找区域设置但找不到它。
代码遗漏了什么?
更新:这似乎是MSVC特有的,在Linux Open SUSE 13.2中使用GCC 4.9和Boost 1.59,程序运行得很好。