2

I have a hex string containing timestamp like this: 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?

  std::string timeString = "00059f4d1832788e";

Edit: It is not only converting a hex string to int. What I need is: Hex string -> long int -> remove millisecond and microsecond part -> convert to time_t -> print it.

Mubin Icyer
  • 608
  • 1
  • 10
  • 21
  • Are you asking how many microseconds are in second? This is not programming question. – Öö Tiib Feb 24 '20 at 10:09
  • No. Timestamp contains timestamp with microsecond. I convert it to long int and divide it to 1000000 to get rid of micro and miliseconds. – Mubin Icyer Feb 24 '20 at 10:18
  • 2
    `std::stoull(timeString, nullptr, 16) / 10e9;` ? It should give you an `unsigned long long` in seconds. I did not post it as an answer since there is already a good one. – Fareanor Feb 24 '20 at 10:23
  • Does this answer your question? [How to convert a hex string to an unsigned long?](https://stackoverflow.com/questions/5934298/how-to-convert-a-hex-string-to-an-unsigned-long) – Öö Tiib Feb 24 '20 at 10:59
  • @Fareanor Good one. I added that but made it `std::stoll`. You never now if you'll get timestamps from before epoch :-) – Ted Lyngmo Feb 24 '20 at 11:04

1 Answers1

6

You can start by using an istringstream or std::stoll to convert the hex timestamp:

#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)

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108