Reputation: 121
I am writing a little program about time, but seems MacBook timezone setting has some problems, my current timezone in System Preferences is JST(UTC+9) now.
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char *argv[]) {
time_t time_in_second;
struct tm *time_today;
time (&time_in_second);
time_t today_in_second = time_in_second - (time_in_second % 86400);
time_today = gmtime(&today_in_second); // will out put 00:00
time_today = localtime(&today_in_second); // will output 09:00
printf ("year: %d\nmonth: %d\nday: %d\nhour: %d\nminuts: %d\nsecond: %d\n", \
1900+time_today->tm_year, 1+time_today->tm_mon,\
time_today->tm_mday, time_today->tm_hour, time_today->tm_min, time_today->tm_sec);
return 0;
}
Shouldn't localtime
output 00:00
instead of gmtime
?
Or I just misunderstanding about this?
How can I fix this? I did some search, but I only get the way to change the operating system timezone setting.
Can I change the hardware timezone to UTC to avoid this problem?
Upvotes: 0
Views: 45
Reputation:
This behavior is correct. time_t
is relative to UTC; performing mathematical operations on a time_t
value (like rounding it down to the nearest day) will give results relative to GMT. If you want to perform these operations relative to your local time zone, you will need to correct for that.
The "hardware timezone" is not relevant to this behavior, and changing it would not have any effect, even if it was possible. (macOS does not support storing the system clock as the local time; this was only ever a standard practice on some older Windows systems.)
Upvotes: 1