7

I represent dates using seconds (and microseconds) since 1970 as well as a time zone and dst flag. I want to print a representation of the date using strftime, but it uses the global value for timezone (extern long int timezone) that is picked up from the environment. How can I get strftime to print the zone of my choice?

richcollins
  • 1,504
  • 4
  • 18
  • 28

2 Answers2

8

The following program sets the UNIX environment variable TZ with your required timezone and then prints a formatted time using strftime.

In the example below the timezone is set to U.S. Pacific Time Zone .

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main (int argc, char *argv[])
{
    struct tm *mt;
    time_t mtt;
    char ftime[10];

    setenv("TZ", "PST8PDT", 1);
    tzset();
    mtt = time(NULL);
    mt = localtime(&mtt);
    strftime(ftime,sizeof(ftime),"%Z %H%M",mt);

    printf("%s\n", ftime);
}
David
  • 14,047
  • 24
  • 80
  • 101
1

Change timezone via setting timezone global variable and use localtime to get the time you print via strftime.

P Shved
  • 96,026
  • 17
  • 121
  • 165