簡體   English   中英

如何將字符串轉換回 time_point?

[英]How do I convert a string back into a time_point?

我正在獲取一個 system_clock time_point,將其轉換為字符串,然后將其保存到配置文件中。

現在我想讀取那個配置文件並將字符串轉回一個時間點,這樣我就可以計算兩個時間點之間的時間差。

void SaveLastShuffleTime() {

    m_lastShuffleTime = std::chrono::system_clock::now();
    auto m_lastShuffleTimeTimeT = std::chrono::system_clock::to_time_t(m_lastShuffleTimeTimepoint);
    stringstream m_lastShuffeTimeSS;
    m_lastShuffeTimeSS << std::put_time(std::localtime(&m_lastShuffleTimeTimeT), "%Y-%m-%d %X");
    m_deviceStateSettings.UpdateDeviceStateSettings(LAST_SHUFFLE_TIME, m_lastShuffeTimeSS.str());
    
} 


void  CompareLastShuffleTime() {

    m _currentShuffleTime = std::chrono::system_clock::now();
    /* READ CONFIG FILE AND CONVERT BACK TO TIME POINT */
    int timeSinceLastShuffle = (duration_cast<minutes>(m_currentShuffleTime - m_oldShuffleTime)).count();
}

請讓我知道這是否可行。 另一種方法是將時間點保存為 integer,但我不想這樣做。

謝謝

我建議輸出 UTC 而不是本地時間,這樣時間戳之間的差異就不會被 UTC 偏移量跳躍(例如夏令時)改變。

C++20 使這變得非常容易,並允許具有亞秒級精度的時間戳:

#include <cassert>
#include <chrono>
#include <iostream>
#include <sstream>

int
main()
{
    using namespace std;
    using namespace std::chrono;
    stringstream s;
    auto tp = system_clock::now();
    auto tp_save = tp;
    s << tp << '\n';          // Write it out
    tp = {};                  // Zero out the timestamp 
    s >> parse("%F %T", tp);  // Parse it back in
    assert(tp == tp_save);    // Make sure it is the same
    std::cout << s.str();     // This is what was formatted/parsed
}

示例 output:

2021-06-17 16:10:10.562738

供應商仍在努力解決這個問題。 但您現在可以將此語法與 C++11/14/17 以及C++20 這部分的免費、開源、僅標頭預覽一起使用。 1個

只需添加:

  • #include "date/date.h"
  • using namespace date;

以上與預覽庫一起使用。


1全面披露:我是這個圖書館的主要作者。 我不會從這項工作中尋求任何經濟利益。 但有時如果我不完全披露這些信息,人們會變得脾氣暴躁。

std::istringstream ss(str);
tm t;
ss >> std::get_time(&t, "%Y-%m-%dT%H:%M:%S");

std::time_t tt = std::mktime(&t);
/// If you don't need UTC time, just comment out the line below.
tt = std::mktime(std::gmtime(&tt));
return std::chrono::system_clock::from_time_t(tt);

你可以使用cctz庫。 它提供了將時間點cctz::format為字符串並從字符串解析cctz::parse的便捷函數。 並且還用於處理時區。 例子:

#include <chrono>
#include <iostream>
#include <string>

#include "cctz/time_zone.h"

int main() {

  const std::chrono::system_clock::time_point now =
      std::chrono::system_clock::now();

  std::string now_str =
      cctz::format("%Y-%m-%d %H:%M:%S%z", now, cctz::utc_time_zone());
  std::cout << now_str << std::endl;

  std::chrono::system_clock::time_point tp;
  const bool ok =
      cctz::parse("%Y-%m-%d %H:%M:%S%z", now_str, cctz::utc_time_zone(), &tp);
  if (!ok)
    return -1;
}

暫無
暫無

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

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