我们经常要遇到时间处理的问题,比如要开发一个schedule的功能,或根据修改时间来过滤文件等。windows API提供了Get*Time()系列函数用于获取当前时间,但是没有提供进行时间转换的,比如我们要得到距离当前时间2年4个月5天的时间,我们就得自己去计算了。但是这里有个问题,如果被减的天数大于当前月份的天数,那么天数就会变成负值。为了解决这个问题,我们就根据不同月份的天数来计算偏移,同时做月和年的变化。不过这种方法很麻烦,因为每个月天数是不同的还需要考虑闰年和平年的问题。其实C的Time系列函数可以很好的解决这个问题,
1. 首先用TM结构进行需要的时间偏移
2. 然后利用mktime这个函数将TM结构转换到从1900.1.1开始的秒数值
3. 再利用localtime 把秒数转换成TM结构
示例代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
#include
"
stdafx.h
"
#include < Windows.h >
#include < time.h >
#include < iostream >
using namespace std;
void OffsetDateTime( const struct tm * inST, struct tm * outST,
int dYears, int dMonths, int dDays,
int dHours, int dMinutes, int dSeconds)
{
if (inST != NULL && outST != NULL)
{
// 偏移当前时间
outST -> tm_year = inST -> tm_year - dYears;
outST -> tm_mon = inST -> tm_mon - dMonths;
outST -> tm_mday = inST -> tm_mday - dDays;
outST -> tm_hour = inST -> tm_hour - dHours;
outST -> tm_min = inST -> tm_min - dMinutes;
outST -> tm_sec = inST -> tm_sec - dSeconds;
// 转换到从1900.1.1开始的总秒数
time_t newRawTime = mktime(outST);
// 将秒数转换成时间结构体
outST = localtime( & newRawTime);
}
}
int _tmain( int argc, _TCHAR * argv[])
{
time_t rawtime;
struct tm * st;
// 获取本地当前时间
time( & rawtime);
st = localtime( & rawtime);
cout << st -> tm_year << " - " << st -> tm_mon << " - " << st -> tm_mday << endl;
// 计算时间偏移
struct tm outst;
OffsetDateTime(st, & outst, 2 , 3 , 20 , 0 , 0 , 0 );
time_t newTime = mktime( & outst);
cout << outst.tm_year << " - " << outst.tm_mon << " - " << outst.tm_mday << endl;
cout << " rawTime: " << rawtime << endl << " newTime : " << newTime << endl;
return 0 ;
}
#include < Windows.h >
#include < time.h >
#include < iostream >
using namespace std;
void OffsetDateTime( const struct tm * inST, struct tm * outST,
int dYears, int dMonths, int dDays,
int dHours, int dMinutes, int dSeconds)
{
if (inST != NULL && outST != NULL)
{
// 偏移当前时间
outST -> tm_year = inST -> tm_year - dYears;
outST -> tm_mon = inST -> tm_mon - dMonths;
outST -> tm_mday = inST -> tm_mday - dDays;
outST -> tm_hour = inST -> tm_hour - dHours;
outST -> tm_min = inST -> tm_min - dMinutes;
outST -> tm_sec = inST -> tm_sec - dSeconds;
// 转换到从1900.1.1开始的总秒数
time_t newRawTime = mktime(outST);
// 将秒数转换成时间结构体
outST = localtime( & newRawTime);
}
}
int _tmain( int argc, _TCHAR * argv[])
{
time_t rawtime;
struct tm * st;
// 获取本地当前时间
time( & rawtime);
st = localtime( & rawtime);
cout << st -> tm_year << " - " << st -> tm_mon << " - " << st -> tm_mday << endl;
// 计算时间偏移
struct tm outst;
OffsetDateTime(st, & outst, 2 , 3 , 20 , 0 , 0 , 0 );
time_t newTime = mktime( & outst);
cout << outst.tm_year << " - " << outst.tm_mon << " - " << outst.tm_mday << endl;
cout << " rawTime: " << rawtime << endl << " newTime : " << newTime << endl;
return 0 ;
}