【问题标题】:Convert Milliseconds to Duration with the given format使用给定格式将毫秒转换为持续时间
【发布时间】:2019-11-05 08:59:59
【问题描述】:

对于给定的持续时间203443毫秒(这是3 分钟、23 秒和443 毫秒),类似于例如的模式

This took about' m 'minutes and' s 'seconds.

会产生以下 格式化输出:

This took about 3 minutes and 23 seconds.

格式时间戳与当前日期时间不同。是否有任何 C++ 标准库(在 C++14 下)或我可以遵循的解决方案。我是 C++ 新手。

【问题讨论】:

  • 您有时间戳或持续时间吗?它们是不同的东西(标准库中的不同类)。你有什么?请尝试创建一个minimal reproducible example 来展示您拥有什么以及您正在尝试做什么,并告诉我们您在使用该示例时遇到了什么问题。或许还需要阅读或刷新how to ask good questions,以及this question checklist
  • 我认为我有一个持续时间。
  • 我没有想出任何解决方案,所以我在这里提出了一个问题。
  • @sephiroth 是的,但我的毫秒需要转换为年:月:天:小时:分钟:秒:毫秒。我已经读过那篇文章了。

标签: c++ c++14 duration chrono


【解决方案1】:
#include <chrono>
#include <iostream>

int
main()
{
    using namespace std::chrono;
    auto d = 203443ms;
    auto m = duration_cast<minutes>(d);
    d -= m;
    auto s = duration_cast<seconds>(d);
    std::cout << "This took about " << m.count() << " minutes and "
                                    << s.count() << " seconds.\n";
}

【讨论】:

  • 我可以将毫秒转换为年:月:日:小时:分钟:秒:毫秒吗?用你刚才给我看的东西??
  • 您似乎是 C++ 中日期时间格式库的大师。
  • 是的。但是,持续时间类型别名 yearsmonthsdays 在 C++14 中不存在。但是您可以创建这样的持续时间,如下所示:github.com/HowardHinnant/date/blob/master/include/date/date.h然而yearsmonths 持续时间类型将是平均年和月的长度。因此,您的消息中的“关于”将是恰当的。
  • 我已经访问了你的 GitHub 上千次,但我不能只使用标准库。感谢您的帮助。
  • 是的,这就是我现在正在做的事情。其实我的问题是日月年,其他类型已经解决了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-12
  • 1970-01-01
相关资源
最近更新 更多