最近有一个小需求:
根据当前日期,求出一周前日期,三个月前日期,一年前日期。
实现如下:
1 调用示例:
//开始时间
COleDateTime startDate;
//结束时间
COleDateTime endDate = COleDateTime::GetCurrentTime();
//最近一周
startDate = CTimeChange::PreDate(endDate, 7, DAY_TYPE);
//最近三个月
startDate = CTimeChange::PreDate(endDate, 3, MONTH_TYPE);
//最近一年
startDate = CTimeChange::PreDate(endDate, 1, YEAR_TYPE);
2 头文件 TimeChange.h:
#pragma once
enum DateType
{
YEAR_TYPE,
MONTH_TYPE,
DAY_TYPE
};
class CTimeChange
{
public:
CTimeChange();
~CTimeChange(void);
//求nSpan前年月日时间
static COleDateTime PreDate(COleDateTime curDate, int nSpan, DateType nType);
//获取查询月天数
static int GetMonthDays(int nYear, int nMonth);
};
3 实现文件TimeChange.cpp:
#include "StdAfx.h"
#include "TimeChange.h"
CTimeChange::CTimeChange()
{
}
CTimeChange::~CTimeChange(void)
{
}
COleDateTime CTimeChange::PreDate(COleDateTime curDate, int nSpan, DateType nType)
{
if (DAY_TYPE == nType)
{
return curDate - COleDateTimeSpan(nSpan, 0, 0, 0);
}
int nYear = curDate.GetYear();
int nMonth = curDate.GetMonth();
int nDay = curDate.GetDay();
if (YEAR_TYPE == nType)
{
nYear -= nSpan;
}
else if (MONTH_TYPE == nType)
{
nMonth -= nSpan;
if (nMonth <= 0)
{
nYear -= 1;
nMonth += 12;
}
}
int nMonthDays = GetMonthDays(nYear, nMonth);
if (nMonthDays < nDay)
{
nDay = nMonthDays;
}
curDate.SetDate(nYear, nMonth, nDay);
return curDate;
}
int CTimeChange::GetMonthDays(int nYear, int nMonth)
{
int nDays = 0;
switch (nMonth)
{
case 2:
//判断闰年
if ((nYear%4==0&&nYear%100!=0)||(nYear%400==0))
{
nDays = 29;
}
else
{
nDays = 28;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
nDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
nDays = 30;
break;
}
return nDays;
}