将 double 转换为 struct tm

Convert double to struct tm

我有一个包含秒数的 double。我想将其转换为 struct tm.

我找不到完成此操作的标准函数。我必须手写 struct tm 吗?

我只是 about converting to a time_t and http://www.whosebug.com不会让我post除非我link它。

嗯,你之前不小心问对了问题。将 double 转换为 time_t,然后将其转换为 struct tmstruct tm 中没有亚秒字段。

对于笑容,使用 this chrono-based header-only library:

#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返回的对象都有getter:

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。您可以选择从 hourspicoseconds 的任何精度(如果您还为 picoseconds 提供类型别名)。例如:

std::cout << make_time(duration_cast<seconds>(recovery_time)) << '\n';

输出:

00:05:20

是正确的,但我想我应该添加一些关于 如何将 转换为 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))));

此处更详细地讨论了转换选项: but once you have obtained your time_t through one of these methods you can simply use localtimetemp 转换为 struct tm

const auto output = *localtime(&temp);

请注意取消引用很重要。它将使用默认的复制赋值运算符,因此 output 按值捕获,这是必不可少的,因为:

The structure may be shared between std::gmtime, std::localtime, and std::ctime, and may be overwritten on each invocation.