簡體   English   中英

有沒有一種標准方法可以在不使用Boost的情況下將std :: string轉換為std :: chrono :: time_point?

[英]Is there a standard way to convert a std::string to std::chrono::time_point without using Boost?

基本上,我正在尋找一種將2014/08/29-11:42:05.042轉換為time_point對象的標准方法。 我知道如何使用boost做到這一點,但是只能使用STL庫嗎? 怎么樣?

如果可以指定%y/%m/%d-%H:%M:%S.%f類的格式,那將是很好的。

好的,至少對於具有毫秒分辨率的固定格式而言,它可以工作。 試圖使該代碼能夠接受任何字符串格式,就像重新發明輪子一樣(即Boost中具有所有功能)。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM