0

タイプの変数を使用して時間の値を編集していますstruct tm(に数秒追加tm->tm_sec) が、実行後に間違った結果が得られmktime(&t)ます。

Linux でこれを行うと適切な結果が得られますが、AIX ではそうではありません。何が問題なのですか?

#include <stdio.h>
#include <time.h>
#include <langinfo.h>
#include <locale.h>
int main ()
{
struct tm tm;
struct tm *end;
time_t t;
char str[20] = {'\0'};

//if (strptime("7 Feb 2013 01:47:30", "%d %b %Y %H:%M:%S", &tm) == NULL)
if (strptime("2012-10-17-01-07-30", "%Y-%m-%d-%H-%M-%S", &tm) == NULL)
{printf("Error\n");
}
tm.tm_sec = (tm.tm_sec + 1200);
//tm.tm_sec = 12;
//t = mktime(&tm);
//t = t + 12;
//end =localtime(&t);
strftime(str,20,"%Y %m %d %H %M %S",&tm);
printf("str is %s\n",str);

return 0;
}
4

2 に答える 2

2

time_t1970 年 1 月 1 日の午前 0 時からの秒数を表す大きな数値であるを使用するのが正解だと思います。ここに任意の秒数を追加するのは非常に簡単です。

に秒を追加するだけtm->tm_secではオーバーフローし、結果が不正確になると思います。運が悪い場合は、変更を 1 年を通して秒単位でリップルする必要があります (2013 年 12 月 31 日 23:59:56 に 5 秒を追加すると、2014 年 1 月 1 日 00:00:01 になります)。もちろん、これは実行できますが、代わりに:

t = + 5;

あなたはの線に沿って約十数のステップを取得します

tm.tm_sec += 5;
if (tm.tm_sec >= 60) { tm.tm_sec -= 60; tm.tm_min += 1; if (tm.tm_min >= 60) { ... など ... } }

1 か月の日数をオーバーフローさせると、さらに面白くなります。各月の日数を考慮に入れる必要があるためです。月によって、28、29、30、または 31 [うるう年の場合]か否か]。

于 2013-02-08T11:40:30.940 に答える
0

これは事実上マッツが言ったことです:

#include <stdio.h>
#include <time.h>
#include <langinfo.h>
#include <locale.h>
int main ()
{
  struct tm tm;
  time_t t;
  char str[20] = {'\0'};

  if (strptime("2012-10-17-01-07-30", "%Y-%m-%d-%H-%M-%S", &tm) == NULL) {
    printf("error\n");
  }
  t = mktime(&tm);
  t += 1200;
  tm = *localtime(&t);
  strftime(str,20,"%Y %m %d %H %M %S",&tm);
  printf("str is %s\n",str);

  return 0;
}

プロデュース:

cc -o t t.c && ./t
str is 2012 10 17 02 27 30
于 2013-02-08T23:57:08.360 に答える