Boost logo

Boost :

From: Jeff Garland (jeff_at_[hidden])
Date: 2003-06-20 08:42:10

> I note that boost::posix_time supports on certain platforms
> the generation of a ptime from a timeval (using gettimeofday()).
> I have a time class in my own project which can be cast from/to
> timeval, so I can use it in conjunction with calls to 'select()',
> which expects a timeval pointer.
> I'd like to replace my code by boost::date_time, but conversion
> from boost::date_time to timeval doesn't seem to be supported.

You are right, but this would make a nice addition.

For your purpose you should probably consider using the
library with microsecond resolution enabled. Basically if
is what you will get (more details in my other response
to your follow on email). Then you won't have to worry
about rounding of nano-second resolution into microseconds.

So then you need a function like:

timeval to_timeval(const boost::posix_time::ptime& t);

As I recall (going from memory without checking!) the first part
of the timeval is a time_t count of seconds since 1/1/1970 00:00:00.
So to get this we can do the following:

     using boost::posix_time;
     ptime timet_start(date(1970,1,1));
     time_duration diff = t - timet_start;
     timeval tv;
     //drop off the fractional seconds...
     tv.tv_sec = diff.ticks()/time_duration::rep_type::res_adjust();
     //The following only works with microsecond resolution!
     tv.tv_usec = diff.fractional_seconds();
     return tv;

This is rough and totally untested, but should get you going.
As an example, ptime can represent dates prior to 1/1/1970,
so the results will be wrong if you use such dates. But if
you are only using time values read from the clock than you
will be safe. Also
     tv.tv_usec = diff.fractional_seconds();
will need to be rounded or adjusted by the resolution if you aren't
using microsecond resolutions.



Boost list run by bdawes at, gregod at, cpdaniel at, john at