簡體   English   中英

std :: string到std :: chrono time_point

[英]std::string to std::chrono time_point

我有一個以下時間格式的字符串:

"%Y-%m-%d %H:%M:%S.%f"

其中%f是毫秒,例如: 14:31:23.946571

我希望這是一個chrono time_point 有演員這樣做嗎?

沒有從std::stringstd::chrono::time_point 您必須構建std::chrono::time_point對象。

  • 使用除微秒之外的所有內容來構造std::tm對象( <ctime> )。 年份應該基於1900而不是0.月份應該基於0而不是1。
  • 使用std::mktime()創建一個std::time_t對象。
  • 使用from_time_t()創建std::chrono::time_point
  • 將剩余的小數部分(視為int )作為std::chrono::microsecond() time_point std::chrono::microsecond() time_point std::chrono::microsecond()持續時間添加到time_point

請注意, <iomanip>函數std::ctime()std::put_time()不知道精度低於一秒。 如果要打印該精度級別,則需要編寫一個函數來執行此操作。

#include <chrono>
#include <ctime>
#include <iomanip>
#include <iostream>

struct Tm : std::tm {
  int tm_usecs; // [0, 999999] micros after the sec

  Tm(const int year, const int month, const int mday, const int hour,
     const int min, const int sec, const int usecs, const int isDST = -1)
      : tm_usecs{usecs} {
    tm_year = year - 1900; // [0, 60] since 1900
    tm_mon = month - 1;    // [0, 11] since Jan
    tm_mday = mday;        // [1, 31]
    tm_hour = hour;        // [0, 23] since midnight
    tm_min = min;          // [0, 59] after the hour
    tm_sec = sec;          // [0, 60] after the min
                           //         allows for 1 positive leap second
    tm_isdst = isDST;      // [-1...] -1 for unknown, 0 for not DST,
                           //         any positive value if DST.
  }

  template <typename Clock_t = std::chrono::high_resolution_clock,
            typename MicroSecond_t = std::chrono::microseconds>
  auto to_time_point() -> typename Clock_t::time_point {
    auto time_c = mktime(this);
    return Clock_t::from_time_t(time_c) + MicroSecond_t{tm_usecs};
  }
};

int main() {
  using namespace std::chrono;

  auto tp_nomicro = Tm(2014, 8, 19, 14, 31, 23, 0).to_time_point();
  auto tp_micro = Tm(2014, 8, 19, 14, 31, 23, 946571).to_time_point();
  std::cout << duration_cast<microseconds>(tp_micro - tp_nomicro).count()
            << " microseconds apart.\n";

  auto time_c = high_resolution_clock::to_time_t(tp_micro);
  std::cout << std::ctime(&time_c) << '\n';
}

暫無
暫無

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

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