Skip to content

Instantly share code, notes, and snippets.

@kosh04
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kosh04/6fbcace234fccbc81cfb to your computer and use it in GitHub Desktop.
Save kosh04/6fbcace234fccbc81cfb to your computer and use it in GitHub Desktop.
mktime, localtime 関数は環境変数 TZ を参照する

実行結果

$ gcc prog/c/timezone.c && TZ=UTC ./a.exe
mktime() = 0
gmtime((t=0,&t))         : Thu Jan 01 00:00:00 1970
localtime((t=0,&t))      : Thu Jan 01 00:00:00 1970
gmtime((t=32400,&t))     : Thu Jan 01 09:00:00 1970
localtime((t=32400,&t))  : Thu Jan 01 09:00:00 1970

$ gcc prog/c/timezone.c && TZ=UTC+9 ./a.exe
mktime() = 32400
gmtime((t=0,&t))         : Thu Jan 01 00:00:00 1970
localtime((t=0,&t))      : Wed Dec 31 15:00:00 1969
gmtime((t=32400,&t))     : Thu Jan 01 09:00:00 1970
localtime((t=32400,&t))  : Thu Jan 01 00:00:00 1970

$ gcc prog/c/timezone.c && TZ= ./a.exe
mktime: Invalid argument

リンク

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <inttypes.h>
int main(int argc, char *argv[])
{
struct tm stm;
time_t t;
tzset();
// 1970-01-01T00:00:00
stm.tm_year = 1970 - 1900;
stm.tm_mon = 1 - 1;
stm.tm_mday = 1;
stm.tm_hour = 0;
stm.tm_min = 0;
stm.tm_sec = 0;
stm.tm_isdst = -1;
t = mktime(&stm);
if (t == -1) {
perror("mktime");
exit(EXIT_FAILURE);
}
printf("mktime() = %ld\n", (long)t);
#define PRINT(x) printf(#x "\t : %s", asctime((x)));
PRINT(gmtime((t=0,&t)));
PRINT(localtime((t=0,&t)));
PRINT(gmtime((t=32400,&t)));
PRINT(localtime((t=32400,&t)));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment