2014-08-29 56 views
1

基本上我正在寻找一种标准的方式来将字符串2014/08/29-11:42:05.042转换为time_point对象。我知道如何用boost来做到这点,但是只能用STL库来完成吗?怎么样?有没有一种标准的方式来将std :: string转换为std :: chrono :: time_point而不使用Boost?

如果可以指定%y/%m/%d-%H:%M:%S.%f之类的格式,这将是一件好事。

+0

相关:?http://stackoverflow.com/questions/21021388 – Rufflewind 2014-08-29 01:46:38

+0

你进行什么研究 – 2014-08-29 01:50:13

+0

@LightnessRacesinOrbit我在升压用time_facet做到了这一点,但我还没有发现任何用STD做这件事的好方法。 – 2014-08-29 02:37:15

回答

1

好吧,至少对于毫秒分辨率的固定格式,这是有效的。试图使这个代码能够接受任何字符串格式就会像重新发明轮子(即有这一切功能的提升。

std::chrono::system_clock::time_point string_to_time_point(const std::string &str) 
{ 
    using namespace std; 
    using namespace std::chrono; 

    int yyyy, mm, dd, HH, MM, SS, fff; 

    char scanf_format[] = "%4d.%2d.%2d-%2d.%2d.%2d.%3d"; 

    sscanf(str.c_str(), scanf_format, &yyyy, &mm, &dd, &HH, &MM, &SS, &fff); 

    tm ttm = tm(); 
    ttm.tm_year = yyyy - 1900; // Year since 1900 
    ttm.tm_mon = mm - 1; // Month since January 
    ttm.tm_mday = dd; // Day of the month [1-31] 
    ttm.tm_hour = HH; // Hour of the day [00-23] 
    ttm.tm_min = MM; 
    ttm.tm_sec = SS; 

    time_t ttime_t = mktime(&ttm); 

    system_clock::time_point time_point_result = std::chrono::system_clock::from_time_t(ttime_t); 

    time_point_result += std::chrono::milliseconds(fff); 
    return time_point_result; 
} 

std::string time_point_to_string(std::chrono::system_clock::time_point &tp) 
{ 
    using namespace std; 
    using namespace std::chrono; 

    auto ttime_t = system_clock::to_time_t(tp); 
    auto tp_sec = system_clock::from_time_t(ttime_t); 
    milliseconds ms = duration_cast<milliseconds>(tp - tp_sec); 

    std::tm * ttm = localtime(&ttime_t); 

    char date_time_format[] = "%Y.%m.%d-%H.%M.%S"; 

    char time_str[] = "yyyy.mm.dd.HH-MM.SS.fff"; 

    strftime(time_str, strlen(time_str), date_time_format, ttm); 

    string result(time_str); 
    result.append("."); 
    result.append(to_string(ms.count())); 

    return result; 
} 

为了测试它,我试过这样的,并确保该字符串正确地表示当前日期时间:

auto tp_src = system_clock::now(); 
string value = time_point_to_string(tp_src); 
auto tp_cnv = string_to_time_point(value); 
auto error = duration_cast<milliseconds>(tp_src - tp_cnv).count(); 
Assert::IsTrue(error == 0); 
相关问题