C ++迄今为止增加了1年 [英] C++ add 1 year to date

查看:98
本文介绍了C ++迄今为止增加了1年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是即时通讯生成我想加1年的日期的方式.预先感谢.

This is how im generating my date i want to add 1 year to it. Thanks in advance.

char tmpbuf[128];
time_t ltime;
struct tm *today;
stringstream reD;
string todayDate;
time( &ltime );
today = localtime( &ltime );
strftime( tmpbuf, 128,"%Y-%m-%d_%H:%M:%S", today );
reD << tmpbuf;
reD >> todayDate;
boost::replace_all(todayDate, "_", " ");
cout << todayDate << endl;

好的,香港专业教育学院决定加倍使用,因为增加天数会更容易,所以我有2个例子需要增加1年,另外1个要增加14天,这就是我目前的票价

OK ive decided to go with boost since it will be easier to add days, so 2 examples i need one to add 1 year, and one to add 14 days, heres what i have so fare

 #include "boost/date_time.hpp"
 #include "boost/date_time/local_time/local_time.hpp"

 using namespace boost::posix_time;
 using namespace boost::local_time;

 int main(){
    local_date_time t = local_sec_clock::local_time(time_zone_ptr());
    local_time_facet* lf(new local_time_facet("%Y-%m-%d_%H:%M:%S"));
    std::cout.imbue(std::locale(std::cout.getloc(), lf));
    std::cout << t << std::endl;
    return 0;
 }

编辑将时间放入字符串

 stringstream reD;
 reD.imbue(locale(reD.getloc(), lf));
 reD << t;
 bthis = reD.str();
 cout << bthis << endl;

推荐答案

我同意使用boost::date_time,但是,这里的解决方案非常简单.

I agree about using boost::date_time, however, the solution here is quite easy.

today->tm_year++;

尽管,如果您碰巧再次调用localtime,则该值将被覆盖,因此您应该进行复制.将today设置为实例而不是指针,并取消引用localtime的返回值,如下所示:

Although, if you happen to call localtime again, the value will be overwritten, so you should make a copy. Make today an instance instead of a pointer, and dereference the return value of localtime like this:

today = *localtime( &ltime );

您必须考虑某些异常情况,例如从February年2月29日起增加一年.

You'll have to take into account certain anomalies, like incrementing a year from February 29th on a leap year.

编辑:我看到您已经决定使用boost::date_time.这使事情变得简单得多.添加年份的方法如下:

I see you've decided to use boost::date_time after all. This makes things much simpler. Here's how you add a year:

t += boost::gregorian::years(1);

这是您增加14天的方法:

And here's how you add 14 days:

t += boost::gregorian::days(14);

t += boost::gregorian::weeks(2);

这篇关于C ++迄今为止增加了1年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆