gpt4 book ai didi

c++ - 如何将包含纪元时间的十六进制字符串转换为time_t?

转载 作者:行者123 更新时间:2023-12-02 03:10:21 25 4
gpt4 key购买 nike

我有一个包含时间戳的十六进制字符串,如下所示:00059f4d1832788e。它包含微秒精度。我只想看第二部分。将其转换为time_t类型的正确方法是什么?

  std::string timeString = "00059f4d1832788e";

编辑:它不仅仅是将十六进制字符串转换为整数。我需要的是:十六进制字符串 -> long int -> 删除毫秒和微秒部分 -> 转换为 time_t -> 打印它。

最佳答案

您可以首先使用 istringstreamstd::stoll 转换十六进制时间戳:

#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

int main() {
std::string timeString = "00059f4d1832788e";

std::istringstream is(timeString);
long long x;
is >> std::hex >> x; // x now contains the value

// or:
// long long x = std::stoll(timeString, nullptr, 16);

// then convert it to a chrono::time_point:
std::chrono::microseconds us(x);
std::chrono::time_point<std::chrono::system_clock> sc(us);

// and finally convert the time_point to time_t
std::time_t t_c = std::chrono::system_clock::to_time_t(sc);

// and print the result
std::cout << std::put_time(std::gmtime(&t_c), "%FT%TZ") << '\n';
std::cout << std::put_time(std::localtime(&t_c), "%FT%T%z (%Z)") << '\n';
}

可能的输出:

2020-02-24T07:12:30Z
2020-02-24T08:12:30+0100 (CET)

关于c++ - 如何将包含纪元时间的十六进制字符串转换为time_t?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60373507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com