この小さなプログラムは、私のプロジェクトでバグを再現します。time_t 変数は struct_tm に変換され、次に文字列に変換され、ファイルにシリアル化されます。後で、この文字列がファイルから読み込まれ、time_t に変換される必要があります。結果の time_t は、元の時間とは 1 時間異なります (おそらく夏時間のため)。ファイル形式は変わらないはずなので、デシリアライズ部分だけ変更できます。
#include "stdafx.h"
#include <iostream>
#include <文字列>
#include <time.h>
名前空間 std を使用します。
文字列 FormatDateTime(struct tm* time);
ボイドテスト();
int _tmain(int argc, _TCHAR* argv[])
{
テスト();
0 を返します。
}
文字列 FormatDateTime(struct tm* time)
{
static const char* months[] =
{
「1月」「2月」「3月」「4月」「5月」「6月」「7月」「8月」「9月」「10月」「11月」「12月」
};
char s[30];
const char* 月;
if (時間->tm_mon >= 0 && 時間->tm_mon < 12)
{
月 = 月[time->tm_mon];
}
そうしないと
{
月 = "??";
}
sprintf(s, "%d-%s-%02d %02d:%02d:%02d",
time->tm_year + 1900、
月、
time->tm_mday、
time->tm_hour、
時間 - > tm_min、
time->tm_sec);
戻り値;
}
ボイドテスト()
{
// time_t 変数は現在の時刻で初期化されます
time_t t = 時間 (NULL);
// time_t 変数は struct tm に変換され、次に string に変換されます
struct tm* ptm = localtime(&t);
文字バッファ[100];
sprintf(buffer, "%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; // 文字列はOK
// 文字列はファイルに保存されます
// ************************************************ ********************************************
// 後でこの文字列がファイルから復元されます
// **** この行の後でのみ何かを変更できます **** //
struct tm stm;
memset(&stm, 0, sizeof(stm));
sscanf(buffer, "%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
struct 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
このプログラムの最後の部分を変更して正しい結果を得るにはどうすればよいですか?