Eto*_*Jr. 4 c++ datetime boost
在一个类中,我有一个属性 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));
Run Code Online (Sandbox Code Playgroud)
我想创建设置方法(添加和减去)该 ptime 的所有字段的值(年、月、日、小时...如果可能的话)。
如果我使用 ptime_.date(),它会返回日期的 cons 引用,并且我无法直接设置它。
我想做这样的事情:
void my_class::set_year(qint64 y) {
// p_.date().year = y;
}
Run Code Online (Sandbox Code Playgroud)
这可能吗?
我正在考虑创建一个 Reset(...) 方法,并设置我需要的内容,但这听起来很奇怪(复制所有值并在代码中重复它们)。
参考值。
在boost ptime的描述中我们可以读到:
boost::posix_time::ptime 类是时间点操作的主要接口。一般来说,ptime 类一旦构造出来就是不可变的,尽管它允许赋值。(...) 提供了用于将 posix_time 对象与 tm 结构相互转换的函数以及从 time_t 和 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);
}
Run Code Online (Sandbox Code Playgroud)
输出:
2002年2月10日 05:04:02
2001年2月10日 05:04:02
| 归档时间: |
|
| 查看次数: |
4894 次 |
| 最近记录: |