Boost logo

Boost Users :

From: Jeff Garland (jeff_at_[hidden])
Date: 2008-05-18 14:26:52


Patrick Loney wrote:
> Using these two isn’t perfect but better than going back to epoch:
>
>
>
> tm to_tm(ptime);
>
> time_t mktime ( struct tm * timeptr );

That's probably fairly inefficient. Part of the reason this isn't in the
library is that there's a number of safety issues when converting back to
time_t (and it hasn't come up much). The code below points out those issues.

This code is completely untested:

   //! Function that converts a ptime into a time_t
   inline
   std::time_t to_time_t(ptime t)
   {
     //if ptime is not_a_date_time or an infinity there's no conversion
     if (t.is_special()) {
        throw some_exception_type("conversion undefined");
     }
     ptime time_t_epoch(gregorian::date(1970,1,1));

     //if ptime is less than 1970-1-1 conversion will fail
     if (t < time_t_epoch) {
        throw some_exception_type("conversion undefined -- less than valid
time_t epoch");
     }
     time_duration td = t - time_t_epoch();
     //cast likely needed to down covert from 64 to 32 bit rep
     //NOTE: all fractional seconds are truncated below...
     return static_cast<std::time_t>(td.total_seconds());
   }

HTH,

Jeff


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net