Blob
1 #include <u.h>2 #include <stdlib.h> /* setenv etc. */3 #define NOPLAN9DEFINES4 #include <libc.h>5 #include <time.h>7 #define _HAVETIMEGM 18 #define _HAVETMZONE 19 #define _HAVETMGMTOFF 111 #if defined(__linux__)12 # undef _HAVETMZONE14 #elif defined(__sun__)15 # undef _HAVETIMEGM16 # undef _HAVETMZONE17 # undef _HAVETMGMTOFF19 #endif21 static Tm bigtm;23 static void24 tm2Tm(struct tm *tm, Tm *bigtm)25 {26 char *s;28 memset(bigtm, 0, sizeof *bigtm);29 bigtm->sec = tm->tm_sec;30 bigtm->min = tm->tm_min;31 bigtm->hour = tm->tm_hour;32 bigtm->mday = tm->tm_mday;33 bigtm->mon = tm->tm_mon;34 bigtm->year = tm->tm_year;35 bigtm->wday = tm->tm_wday;36 strftime(bigtm->zone, sizeof bigtm->zone, "%Z", tm);37 #ifdef _HAVETMGMTOFF38 bigtm->tzoff = tm->tm_gmtoff;39 #endif41 if(bigtm->zone[0] == 0){42 s = getenv("TIMEZONE");43 if(s){44 strecpy(bigtm->zone, bigtm->zone+4, s);45 free(s);46 }47 }48 }50 static void51 Tm2tm(Tm *bigtm, struct tm *tm)52 {53 memset(tm, 0, sizeof *tm);54 tm->tm_sec = bigtm->sec;55 tm->tm_min = bigtm->min;56 tm->tm_hour = bigtm->hour;57 tm->tm_mday = bigtm->mday;58 tm->tm_mon = bigtm->mon;59 tm->tm_year = bigtm->year;60 tm->tm_wday = bigtm->wday;61 #ifdef _HAVETMZONE62 tm->tm_zone = bigtm->zone;63 #endif64 #ifdef _HAVETMGMTOFF65 tm->tm_gmtoff = bigtm->tzoff;66 #endif67 }69 Tm*70 p9gmtime(long x)71 {72 time_t t;73 struct tm tm;75 t = (time_t)x;76 tm = *gmtime(&t);77 tm2Tm(&tm, &bigtm);78 return &bigtm;79 }81 Tm*82 p9localtime(long x)83 {84 time_t t;85 struct tm tm;87 t = (time_t)x;88 tm = *localtime(&t);89 tm2Tm(&tm, &bigtm);90 return &bigtm;91 }93 #if !defined(_HAVETIMEGM)94 static time_t95 timegm(struct tm *tm)96 {97 time_t ret;98 char *tz;99 char *s;101 tz = getenv("TZ");102 putenv("TZ=");103 tzset();104 ret = mktime(tm);105 if(tz){106 s = smprint("TZ=%s", tz);107 if(s)108 putenv(s);109 }110 return ret;111 }112 #endif114 long115 p9tm2sec(Tm *bigtm)116 {117 struct tm tm;119 Tm2tm(bigtm, &tm);120 if(strcmp(bigtm->zone, "GMT") == 0 || strcmp(bigtm->zone, "UCT") == 0)121 return timegm(&tm);122 return mktime(&tm); /* local time zone */123 }