[英]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.