1. 首先用TM结构进行需要的时间偏移
2. 然后利用mktime这个函数将TM结构转换到从1900.1.1开始的秒数值
3. 再利用localtime 把秒数转换成TM结构
示例代码如下:
#include "stdafx.h"
#include
#include
#include
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_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;
}