3
auto timeSinceEpoch = boost::chrono::duration_cast<boost::chrono::microseconds>(boost::chrono::steady_clock::now().time_since_epoch()).count();

boost::posix_time::ptime now(boost::gregorian::date(1970, 1, 1), boost::posix_time::microsec(static_cast<std::int64_t>(timeSinceEpoch)));

std::string str = boost::posix_time::to_iso_string(now);

Output : 19700114T232422.133653 which it is incorrect, what am I doing wrong ?

Guillaume Paris
  • 10,303
  • 14
  • 70
  • 145

1 Answers1

5

On some systems, the epoch of steady_clock is nanoseconds since boot.

You will get a more useful expected result with other clocks:

Live On Coliru

#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/chrono.hpp>
#include <string>
#include <iostream>

int main()
{
    boost::posix_time::ptime const time_epoch(boost::gregorian::date(1970, 1, 1));

    auto ms = (boost::posix_time::microsec_clock::local_time() - time_epoch).total_microseconds();
    std::cout << "microseconds: " << ms << "\n";

    boost::posix_time::ptime now = time_epoch + boost::posix_time::microseconds(ms);
    std::cout << boost::posix_time::to_iso_string(now);
}

Prints

microseconds: 1415115992000000
20141104T154632
Guillaume Paris
  • 10,303
  • 14
  • 70
  • 145
sehe
  • 374,641
  • 47
  • 450
  • 633
  • I don't precise it but I need to get microseconds precision – Guillaume Paris Nov 04 '14 at 15:47
  • this code is problematic because it doesn't account the fact that boost::posix_time::microsec_clock::local_time() assumes in UTC time. Let's say today is 2022-1-8 20:00:00, but your computer is running in New York Eastern Time. The code (boost::posix_time::microsec_clock::local_time() - time_epoch).total_microseconds() will gives you the epoch microseconds of 2022-1-8 20:00:00 UTC instead of EST – Bob Jan 09 '22 at 01:56