如何将boost local_date_time转换为time_t

时间:2014-05-12 15:54:02

标签: c++ boost localtime time-t

我有:

time_t dataFromTodayByAddingYearsMonthsDays(int years, int months, int days)
{        
    using namespace boost::local_time;

    local_date_time local = local_sec_clock::local_time(time_zone_ptr());
    local += boost::gregorian::years(years);
    local += boost::gregorian::months(months);
    local += boost::gregorian::days(days);

    return ???;
}

如何将此提升local_date_time野兽转换为time_t

2 个答案:

答案 0 :(得分:4)

这里是答案的结晶:

time_t to_time_t(boost::posix_time::ptime const& pt) //! assumes UTC
{
    return (pt - boost::posix_time::from_time_t(0)).total_seconds();
}

我会更简洁地写下日期计算,而你还是会这样做:

int main()
{
    using namespace boost::local_time;

    auto now  = local_sec_clock::local_time(time_zone_ptr()),
         then = now + ymd_duration { 1, 3, -4 };

    std::cout << now  << ", " << to_time_t(now.utc_time())  << "\n";
    std::cout << then << ", " << to_time_t(then.utc_time()) << "\n";
}

查看 Live On Coliru ,打印

2014-May-12 21:50:06 UTC, 1399931406
2015-Aug-08 21:50:06 UTC, 1439070606

Full Code

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/date_time/local_time/local_time_io.hpp>

struct ymd_duration { int years, months, day; };

template <typename T>
T operator+(T const& pt, ymd_duration delta)
{
    using namespace boost::gregorian;
    return pt + years(delta.years) + months(delta.months) + days(delta.day);
}

time_t to_time_t(boost::posix_time::ptime const& pt) //! assumes UTC
{
    return (pt - boost::posix_time::from_time_t(0)).total_seconds();
}

int main()
{
    using namespace boost::local_time;

    auto now  = local_sec_clock::local_time(time_zone_ptr()),
         then = now + ymd_duration { 1, 3, -4 };

    std::cout << now  << ", " << to_time_t(now.utc_time())  << "\n";
    std::cout << then << ", " << to_time_t(then.utc_time()) << "\n";
}

答案 1 :(得分:1)

time_t dataFromTodayByAddingYearsMonthsDays(int years, int months, int days)
{
    using namespace boost::local_time;
    using namespace boost::posix_time;

    local_date_time local = local_sec_clock::local_time(time_zone_ptr());
    local += boost::gregorian::years(years);
    local += boost::gregorian::months(months);
    local += boost::gregorian::days(days);

    ptime utc = local.utc_time();
    ptime epoch(boost::gregorian::date(1970, 1, 1));
    time_duration::sec_type diff = (utc - epoch).total_seconds();

    return time_t(diff);
}