johns193
johns193

Reputation: 61

C++ boost get unix timestamp in UTC

Hello I'm trying to get time elapsed since epoch using boost in UTC but it seems that microsec_clock::universal_time(); doesn't return UTC time, instead it returns time in timezone of PC.

How can I get current time in miliseconds in UTC using boost?

Here is my code that I'm using

const long long unix_timestmap_now()
{ 
   ptime time_t_epoch(date(1970, 1, 1));
   ptime now = microsec_clock::universal_time();
   time_duration diff = now - time_t_epoch;
   return  diff.total_milliseconds();;
}

Upvotes: 1

Views: 4582

Answers (1)

Max ZS
Max ZS

Reputation: 175

Why you use a boost? All needed (which refers to the time) moved to the STL in C ++ .

It is important - not everyone knows that "unix timestamp" at a time is the same for the whole world, ie if the check time on the server in Russia, and for example on a server in the USA, the value will be the same (of course under the condition that both servers correct time right), it differs only in its transformation into understandable for people of form, depending on the server settings. And of course the reverse priobrazovanie will also vary if you do not set the time zone.

Tested on cpp.sh

#include <iostream>
#include <chrono>

int main ()
{
  using namespace std::chrono;

  system_clock::time_point tp = system_clock::now();
  system_clock::duration dtn = tp.time_since_epoch();

  std::cout << "current time since epoch, expressed in:" << std::endl;
   std::cout << "milliseconds: " << duration_cast<milliseconds>(dtn).count();
  std::cout << std::endl;

  return 0;
}

Upvotes: 2

Related Questions