日期倒推

vc中只提供了一个类CTimeSpan类根据“天”数来倒退日期,但在很多查询任务中需要用到倒推几个月或几年来获取起始时间,此时就不能简单的应用CTimeSpan类来实现了。网上没有找到相关的代码,就自己动手写了一下,下面四个函数分别实现倒推**天/**周/**月/**年,得到新的时间信息。


CTime OnGetLastDays(CTime curTime, int nDays)

{
CTime t1(curTime.GetYear(), curTime.GetMonth(), curTime.GetDay(), 0, 0, 0);
CTimeSpan ts(nDays, 0, 0, 0);
t1 = t1-ts;

return t1;
}


CTime OnGetLastWeeks(CTime curTime, int nWeeks)
{
return OnGetLastDays(curTime, 7*nWeeks);
}


CTime OnGetLastMonths(CTime curTime, int nMonths)
{
static int days[] = {31, 28, 31, 30, 31, 30 , 31, 31, 30, 31, 30, 31};


int nYear = curTime.GetYear();
int nMonth = curTime.GetMonth()-nMonths;
int nDay = curTime.GetDay();


if(nMonth < 1)
{
nYear -= 1;
nMonth += 12;
}


if(nDay > days[nMonth-1])
{
nDay = days[nMonth-1];
if(nMonth == 2)
{
//判断是否为闰年
if(My_IsLeapYear(nYear))
nDay = 29;
}
}


curTime = CTime(nYear, nMonth, nDay, 0, 0, 0);
return curTime;
}


CTime OnGetLastYears(CTime curTime, int nYears)
{
static int days[] = {31, 28, 31, 30, 31, 30 , 31, 31, 30, 31, 30, 31};


int nYear = curTime.GetYear()-nYears;
int nMonth = curTime.GetMonth();
int nDay = curTime.GetDay();

for(int i=0;i<nYears;i++)
{
if(My_IsLeapYear(nYear+i))
nDay -= 1;
}

if(nDay < 1)
{
nMonth -= 1;
nDay += days[nMonth-1];
}
else
{
if(nDay > days[nMonth-1])
{
nDay = days[nMonth-1];
if(nMonth == 2)
{
//判断是否为闰年
if(My_IsLeapYear(nYear))
nDay = 29;
}
}
}

curTime = CTime(nYear, nMonth, nDay, 0, 0, 0);


return curTime;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值