gpt4 book ai didi

c++ - 如何将 boost local_date_time 转换为 time_t

转载 作者:搜寻专家 更新时间:2023-10-31 00:35:35 25 4
gpt4 key购买 nike

我有:

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 ???;
}

如何将此 boost local_date_time 野兽转换为 time_t

最佳答案

这是答案的重点:

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

完整代码:

#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";
}

关于c++ - 如何将 boost local_date_time 转换为 time_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23613558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com