2014-11-13 6 views
4

다음과 같은 밀리/마이크로 초 정확도 문자열을 사용하여 일종의 부스트 datetime을 구문 분석합니다.부스트, 다음 문자열을 날짜/시간으로 구문 분석하는 방법

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

나는 패싯에 관한 문서를 보았습니다. 이 같은 것

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

그러나 나는 그들을 어떻게 사용하는지 모른다.

는 I에 유래에서 소기 코드로이 프로그램을 시도,하지만 난 밀리 초가 표시 할 수 없습니다

#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; 
} 
+0

을 준다? 어떤 메시지? 최소한의 예를 제공해주십시오. – tillaert

답변

5

boost::posix_time::time_from_string은 매우 견고이 형식을 구문 분석에 올 때.

std::string에서 boost::posix_time::ptime을 만드는 다른 방법을 찾고 있습니다. 당신은 같은 형식과 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 
+0

이제 t가 셀과 같음을 확인하기 위해 문자열로 변환하려면 원 래, 무엇을 호출해야합니까? – Ivan

+0

감사합니다. – Ivan