There are several ways to do this.
(1) You can set the environment variable TZ
before running your program, as suggested by @Useless in a comment.
(2) You can set the environment variable TZ
from within your program, using the putenv
or setenv
calls. After doing that, you must call tzset()
to tell the timezone machinery in the C library to reexamine the environment variable. Here's your program, fleshed out with the necessary calls to setenv
and tzset
for comparison. (See also @Jonathan Leffler's answer for an example using putenv
.)
sp = localtime(&now);
printf("%d/%d/%02d %d:%02d %s\n",
sp->tm_mon + 1, sp->tm_mday,
1900 + sp->tm_year, sp->tm_hour,
sp->tm_min, tzname[sp->tm_isdst]);
setenv("TZ", "America/Los_Angeles", 1);
tzset();
sp = localtime(&now);
printf("%d/%d/%02d %d:%02d %s\n",
sp->tm_mon + 1, sp->tm_mday,
1900 + sp->tm_year, sp->tm_hour,
sp->tm_min, tzname[sp->tm_isdst]);
(3) You might be able to use the BSD tzalloc
and localtime_rz
functions to directly convert to a specified local time zone:
timezone_t tzp = tzalloc("America/Los_Angeles");
if(tzp == NULL) { fprintf(stderr, "no such zone\n"); exit(1); }
struct tm tmbuf;
sp = localtime_rz(tzp, &now, &tmbuf);
printf("%d/%d/%02d %d:%02d %s\n",
sp->tm_mon + 1, sp->tm_mday,
1900 + sp->tm_year, sp->tm_hour,
sp->tm_min, sp->tm_zone);
(In this last example, I have quietly used a completely different method of printing the time zone name.)
Everything else being equal, I would say that #3 is vastly preferable, since passing an explicit argument to a function — in this case, passing tzp
to localtime_rz()
— is much, much cleaner than manipulating a global variable. Unfortunately, however, the tzalloc
and localtime_rz
functions are not standard, and they're actually rather rare these days, so I won't be at all surprised if they're not available to you. See also this answer.