gpt4 book ai didi

c++ - 在 boost::posix_time 中设置值(年、月、日...)

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:36:36 25 4
gpt4 key购买 nike

在一个类中,我有一个属性 boost::posix_time::ptime,它指的是这样的日期和时间:

boost::posix_time::ptime p_;

在构造函数中,我可以毫无问题地传递值和设置它们。

my_class::my_class( ... )
: p_( boost::posix_time::ptime( boost::gregorian::date(y,M,d),
hours(h) + minutes(m) + seconds(s) +
milliseconds(ms) + microseconds(us) +
nanosec(ns));

我想为这个 ptime 的所有字段(年、月、日、小时......如果可能的话)创 build 置方法(加减)值。

如果我使用 ptime_.date(),它返回一个日期的 cons 引用,我不能直接设置它。

我想做这样的事情:

void my_class::set_year(qint64 y) {
// p_.date().year = y;
}

这可能吗?

我正在考虑创建一个 reset(...) 方法,并设置我需要的东西,但这样做听起来很奇怪(复制所有值并在代码中重复它们)。

研发。

最佳答案

boost ptime的描述中我们可以阅读:

The class boost::posix_time::ptime is the primary interface for time point manipulation. In general, the ptime class is immutable once constructed although it does allow assignment. (...) Functions for converting posix_time objects to, and from, tm structs are provided as well as conversion from time_t and FILETIME.

因此可以使用到时间 struct tm 的转换。此代码段演示了这一点。

#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/date.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
/*
*
*/

using namespace boost::posix_time;
using namespace boost::gregorian;

void set_year( uint64_t y, ptime& p) {
tm pt_tm = to_tm( p);
pt_tm.tm_year = y - 1900;
p = ptime_from_tm( pt_tm);
}

int main(int argc, char** argv) {
ptime t1( date(2002,Feb,10), hours(5)+minutes(4)+seconds(2));
std::cout << to_simple_string( t1) << std::endl;
set_year( 2001, t1);
std::cout << to_simple_string( t1);
}

输出:

2002 年 2 月 10 日 05:04:02

2001 年 2 月 10 日 05:04:02

关于c++ - 在 boost::posix_time 中设置值(年、月、日...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23093430/

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