【问题标题】:C++: how do I convert a string that's a unix time to *tm? (Error using strptime: "cannot convert 'String' to 'tm*' ")C++:如何将 unix 时间的字符串转换为 *tm? (使用 strptime 时出错:“无法将 'String' 转换为 'tm*'”)
【发布时间】:2019-03-24 16:51:18
【问题描述】:

我正在使用 API 来检索 UNIX 时间,但它以字符串形式出现,即“1539944398000”

我想将其转换为 UNIX 时间,以便我可以对其进行操作(并最终仅提取小时/分钟以进行打印)。

这是我尝试过的代码:

String nextBusScheduled = client2.readStringUntil('<');
char bufScheduled[40];
strptime(bufScheduled, "%Y-%m-%d", nextBusScheduled);

这是我得到的错误:

cannot convert 'String' to 'tm*' for argument '3' to 'char* strptime(const char*, const char*, tm*)' 

【问题讨论】:

  • 在 C 中没有原生的 string 类型。是 char * 的 typedef 吗?
  • 这是 C++ 吗? String 实际上是 std::string 还是别的什么?
  • 如果您有一个包含 Unix 时间戳的字符串,您可以使用 strtoll 将其转换为 time_t,然后通过调用 localtimegmtime 将其转换为 struct tm
  • 您的代码中没有 struct tm 变量。 strptime 的第三个参数是它应该解码成的 struct tm *。那你为什么要传递别的东西?当你的输入不是那种格式时,你为什么要求它解析%Y-%m-%d
  • 1539944398000 看起来不像 Unix 时间。如果是 1539944398,那将是 10 月 19 日(即今天)白天的某个时间。但看起来有人会在几微秒内给你。

标签: c++ datetime time unix-timestamp


【解决方案1】:

我推荐Howard Hinnant's date/time library。对于本练习,您只需要 date.h 标头(并且没有来源):

#include "date/date.h"
#include <chrono>
#include <cstdint>
#include <iostream>
#include <sstream>

int
main()
{
    using namespace date;
    using namespace std;
    using namespace std::chrono;
    int64_t i;
    istringstream in{"1539944398000"};
    in >> i;
    sys_time<milliseconds> tp{milliseconds{i}};
    cout << tp << '\n';
    cout << format("%H:%M", tp) << '\n';
}

只需解析为 64 位整数类型,然后从该解析中构造一个 std::chrono::milliseconds(到目前为止,这只是直接的 C++11)。然后你可以从中构造一个sys_time&lt;milliseconds&gt;sys_time&lt;milliseconds&gt; 只是 std::chrono::time_point&lt;std::chrono::system_clock, std::chrono::milliseconds&gt; 的类型别名,或者更简单地说:具有毫秒精度的 Unix Time

我展示了两种打印方式,这正是date.h 真正有用的地方。此示例输出:

2018-10-19 10:19:58.000
10:19

只需删除 #include "date/date.h"using namespace date;,此代码即可移植到 C++20。

【讨论】:

    猜你喜欢
    • 2022-09-22
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    • 2022-01-24
    • 2015-09-09
    • 2015-05-06
    • 2023-03-17
    相关资源
    最近更新 更多