c++ - Incorrect time calculation with mktime to get UTC+8 -
i want current time in hong kong (utc+8), , local time utc-5.
using , running following in vs2012:
#pragma warning(disable : 4996) char buffer[10]; time_t rawtime; time(&rawtime); strftime(buffer, 10, "%h:%m:%s", localtime(&rawtime)); cout << "localtime=" << buffer << endl; strftime(buffer, 10, "%h:%m:%s", gmtime(&rawtime)); cout << "gmtime=" << buffer << endl; tm* r = gmtime(&rawtime); r->tm_hour += 8; // hong kong time mktime(r); // normalize struct strftime(buffer, 10, "%h:%m:%s", r); cout << "hongkongtime=" << buffer << endl;
produces following output:
localtime=22:51:47 gmtime=02:51:47 hongkongtime=11:51:47
so it's computing utc correctly, adding 8 hours producing time utc +9. what's going wrong?
and there more elegant/reliable way of getting utc+8 kludge?
you use localtime
after changing tz
environment variable desired timezone:
#include <iostream> #include <stdlib.h> #include <time.h> int main(){ _putenv_s( "tz", "gmt-08:00" ); time_t mytime = time( null ); struct tm* mytm = localtime( &mytime ); std::cout << "current local time , date: " << asctime(mytm); return 0; }
the object mytime
receive result of function time()
amount of seconds since 00:00 hours, jan 1, 1970 utc
, current unix timestamp. localtime()
use value pointed mytime
fill tm
structure values represent corresponding time, expressed local timezone.
by default, timezone used localtime()
1 used in computer. however, can change function _putenv_s()
, in manipulated tz
variable , added new definition gmt-08:00
timezone hong kong.
in posix systems, user can specify time zone means of tz environment variable.
note more standard way of manipulating tz
variable using function int setenv (const char *name, const char *value, int replace)
wasn't defined in sample, used alternative.
you can read more tz environment variable here
Comments
Post a Comment