[英]Convert double to struct tm
我有一個包含秒的double
。 我想將其轉換為struct tm
。
我找不到實現此目的的標准函數。 我必須手動填寫struct tm
嗎?
我只是無意中問了有關轉換為time_t
,除非鏈接,否則http://www.StackOverflow.com不會讓我發帖。
好吧,您之前不小心問了正確的問題。 將double
轉換為time_t
,然后將其轉換為struct tm
。 無論如何,在struct tm
沒有亞秒字段。
對於咧嘴笑,請使用以下基於chrono
的僅標頭庫 :
#include "date.h"
#include <iostream>
int
main()
{
using namespace std::chrono;
using namespace date;
auto recovery_time = 320.023s; // Requires C++14 for the literal 's'
std::cout << make_time(duration_cast<milliseconds>(recovery_time)) << '\n';
}
輸出:
00:05:20.023
如果要查詢每個字段, make_time
返回的對象都有吸氣劑:
constexpr std::chrono::hours hours() const noexcept {return h_;}
constexpr std::chrono::minutes minutes() const noexcept {return m_;}
constexpr std::chrono::seconds seconds() const noexcept {return s_;}
constexpr precision subseconds() const noexcept {return sub_s_;}
您無需選擇milliseconds
。 您可以選擇所需的精度,從hours
到picoseconds
(如果您還為picoseconds
提供類型別名)。 例如:
std::cout << make_time(duration_cast<seconds>(recovery_time)) << '\n';
輸出:
00:05:20
MSalters的回答是正確的,但我想我將對如何轉換為time_t
以及如何轉換為tm
添加一些細節。
因此,在double input
給出幾秒鍾的時間,您可以使用依賴於實現的強制轉換方法:
const auto temp = static_cast<time_t>(input);
但是由於time_t
是實現定義的,所以沒有辦法知道這是可以簡單地轉換為的原語。 因此,保證的方法將是使用chrono庫的獨立於實現的轉換方法:
const auto temp = chrono::system_clock::to_time_t(chrono::system_clock::time_point(chrono::duration_cast<chrono::seconds>(chrono::duration<double>(input))));
轉換選項在此處進行了更詳細的討論: https : //stackoverflow.com/a/50495821/2642059,但是一旦通過這些方法之一獲得了time_t
,您就可以簡單地使用localtime
將temp
轉換為struct tm
。
const auto output = *localtime(&temp);
請注意,取消引用很重要。 它將使用默認的副本分配運算符,以便按值捕獲output
,這是必不可少的,因為:
該結構可以在
std::gmtime
,std::localtime
和std::ctime
之間共享,並且可能在每次調用時被覆蓋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.