我有double
秒。我想将其转换为struct tm
。
我无法找到完成此任务的标准功能。我必须手动填写struct tm
吗?
我只是accidentally asked this关于转换为time_t
和http://www.StackOverflow.com不会让我发布,除非我链接它。
答案 0 :(得分:4)
嗯,你之前不小心问了正确的问题。将double
转换为time_t
,然后将其转换为struct tm
。无论如何,struct tm
中没有亚秒字段。
答案 1 :(得分:2)
对于笑脸,使用this chrono
-based header-only library:
result = str(~any(triu(bsxfun(@eq, str, str.'), 1)));
输出:
#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
返回的对象具有getter:
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';
答案 2 :(得分:0)
MSalters answer是正确的,但我想我会在 上添加一些细节,以便转换为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
之间共享,也可以在每次调用时覆盖。