Luke
Luke

Reputation: 5971

How to compare boost::posix_time::ptime to milliseconds?

This is what i want to do:

const boost::posix_time::ptime now =
boost::posix_time::microsec_clock::local_time();
if (m_time != NULL && now - *m_time > this->m_iMediatime * 1000)
{
}

Which does not work because of the comparison

Then I tried constructing a ptime object, but I found no constructor that accepts milliseconds as integers, longs or similiar.

Finally I tried to get milliseconds from the ptime object but could not found a suitable method.

the type of m_time is boost::posix_time::ptime

Upvotes: 2

Views: 3520

Answers (2)

sehe
sehe

Reputation: 392863

I'd write it as

if (m_time != NULL)
{ 
    auto delta = now - *m_time;
    if (delta > pt::milliseconds(this->m_iMediatime * 1000))

Here's a full example:

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>

namespace pt = boost::posix_time;

struct Dummy
{
    std::unique_ptr<pt::ptime> m_time;
    int m_iMediatime = 1; // seconds

    Dummy() : m_time(new pt::ptime(pt::microsec_clock::local_time()))
    {
    }

    void foo() const
    {
        const pt::ptime now = pt::microsec_clock::local_time();

        if (m_time != NULL)
        { 
            auto delta = now - *m_time;
            if (delta > pt::milliseconds(this->m_iMediatime * 1000))
            {
                std::cout << "yay\n";
            }
            else
            {
                std::cout << "nay\n";
            }
        }
    }
};

int main()
{
    Dummy o;
    o.foo();

    boost::this_thread::sleep_for(boost::chrono::seconds(2));

    o.foo();
}

See it Live On Coliru, output:

nay
yay

Upvotes: 1

diverscuba23
diverscuba23

Reputation: 2185

I think you want to look at something like boost::posix_time::milliseconds that is a time durration. Assuming that in your example above m_time is a pointer to a boost::posix_time::ptime object, if you change m_iMediaTime to be a boost::posix_time::time_durration and initialize it ussing boost::posix_time::milliseconds(value) then the if statement can become:

if (m_time != NULL && now - *m_time > this->m_iMediatime)
{
}

and should work just fine for you.

Upvotes: 0

Related Questions