日期倒推

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章