简体   繁体   English

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

[英]How to convert hex string containing epoch time to time_t?

I have a hex string containing timestamp like this: 00059f4d1832788e .我有一个包含时间戳的十六进制字符串,如下所示: 00059f4d1832788e It contains microsecond accuracy.它包含微秒精度。 I want to get only up to second part.我只想到第二部分。 What is the correct way to convert it to time_t type?将其转换为 time_t 类型的正确方法是什么?

  std::string timeString = "00059f4d1832788e";

Edit: It is not only converting a hex string to int.编辑:它不仅将十六进制字符串转换为 int。 What I need is: Hex string -> long int -> remove millisecond and microsecond part -> convert to time_t -> print it.我需要的是:十六进制字符串 -> long int -> 删除毫秒和微秒部分 -> 转换为 time_t -> 打印它。

You can start by using an istringstream or std::stoll to convert the hex timestamp:您可以首先使用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';
}

Possible output:可能的输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM