这个小程序重现了我项目中的错误。time_t 变量转换为 struct_tm,然后转换为字符串,并序列化为文件。稍后,从文件中加载此字符串,并应将其转换回 time_t。结果 time_t 与原始时间相差一小时(可能是因为夏令时)。我只能更改反序列化部分,因为文件格式应该保持不变。
#include “stdafx.h”
#include <iostream>
#include <字符串>
#include <时间.h>
使用命名空间标准;
string FormatDateTime(struct tm* time);
无效测试();
int _tmain(int argc, _TCHAR* argv[])
{
测试();
返回0;
}
string FormatDateTime(struct tm* time)
{
静态 const char* 月[] =
{
“一月”、“二月”、“三月”、“四月”、“五月”、“六月”、“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月”
};
字符 [30];
const char* 月;
如果(时间->tm_mon >= 0 && 时间->tm_mon < 12)
{
月 = 月[时间->tm_mon];
}
别的
{
月 = "??";
}
sprintf(s, "%d-%s-%02d %02d:%02d:%02d",
时间->tm_year + 1900,
月,
时间->tm_mday,
时间->tm_hour,
时间->tm_min,
时间->tm_sec);
返回 s;
}
无效测试()
{
// time_t 变量用当前时间初始化
time_t t = 时间(NULL);
// time_t 变量先转换为 struct tm 然后再转换为字符串
结构 tm* ptm = localtime(&t);
字符缓冲区[100];
sprintf(缓冲区,“%d %d %d %d %d %d”,
ptm->tm_mday, ptm->tm_mon + 1, ptm->tm_year + 1900, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
cout << 缓冲区 << endl; // 字符串没问题
// 字符串保存到文件中
// ************************************************ ************************************************
// 稍后这个字符串会从文件中恢复
// **** 我只能在这一行之后改变一些东西 **** //
结构 tm stm;
memset(&stm, 0, sizeof(stm));
sscanf(缓冲区, "%d %d %d %d %d %d",
&stm.tm_mday, &stm.tm_mon, &stm.tm_year, &stm.tm_hour, &stm.tm_min, &stm.tm_sec);
stm.tm_mon -= 1;
stm.tm_year -= 1900;
字符串 s = FormatDateTime(ptm);
cout << s << endl; // 好的
// ************************************************ ************************************************
// 现在我需要将 struct tm 转换为 time_t 并将其保存在变量中
time_t t1 = mktime(&stm); // 不同的时间 - 1 小时的差异
如果 ( t1 == t )
{
cout << "t1 == t" << endl;
}
别的
{
cout << "t1 != t !!!!!" <<endl;
}
// 打印 time_t - 结果不正确
// 实用程序::FormatDateTime
结构 tm* ptm1 = localtime(&t1);
s = FormatDateTime(ptm1);
cout << s << endl;
}
当地时间是 11.33。结果:
19 7 2012 11 33 17 2012-7-19 11:33:17 t1 != t !!!!! 2012-7-19 12:33:17
如何更改该程序的最后一部分以获得正确的结果?