Question

I am trying to retrieve Current Time in milliseconds using boost library.. Below is my code which I am using to get the current time in milliseconds.

boost::posix_time::ptime time = boost::posix_time::microsec_clock::local_time();
boost::posix_time::time_duration duration( time.time_of_day() );
std::cout << duration.total_milliseconds() << std::endl;

uint64_t timestampInMilliseconds = duration.total_milliseconds() // will this work or not?

std::cout << timestampInMilliseconds << std::endl;

But this prints out in 10 digit which is like 17227676.. I am running my code on my ubuntu machine.. And I believe it is always 13 digit long value? Isn't so?

After computing the timestamp in milliseconds, I need to use below formula on that -

int end = (timestampInMilliseconds / (60 * 60 * 1000 * 24))  % 14

But somehow I am not sure whether timestampInMilliseconds which I am getting is right or not?

First of all should I be using boost::posix or not? I am assuming there might be some better way.. I am running code on my ubuntu machine..

Update:-

As this piece of bash script prints out timestampInMilliseconds which is of 13 digit..

date +%s%N | cut -b1-13
Was it helpful?

Solution

The problem here is that you use time_of_day() which returns (from this reference)

Get the time offset in the day.

So from the value you provided in the question I can deduce that you ran this program at 4:47 am.

Instead you might want to use e.g. the to_tm() to get a struct tm and construct your time in milliseconds from there.

Also note that the %s format to the date command (and the strftime function) is the number of seconds since the epoch, not the number of milliseconds.


If you look at the tm structure, you will see that it has the number of years (since 1900, so subtract 70 here), days into the year, and then hours,, minutes and seconds into the day. All these can be used to calculate the time in seconds easily.

And that in seconds is the problem here. If you look at e.g. the POSIX time function you see that

shall return the value of time in seconds since the Epoch

If you want an accurate millisecond resolution you simply can't use the ptime (where the p stands for POSIX). If you want millisecond resolution you either have to use e.g. system functions that returns the time in higher resolutions (like gettimeofday), or you can see e.g. this old SO answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top