假设:time_t
是从一天开始的秒数 - 通用时间。这通常是 1970 年 1 月 1 日 UTC,假定代码使用给定sys/time.h
主要思想是从每个成员中提取tv,tz
数据以形成本地时间。Time-of-day ,UTC,以秒为单位tv.tv_sec
,从时区偏移开始的分钟数和每个 DST 标志的小时调整。最后,确保结果在主要范围内。
各种类型的关注点包括tv
未指定为的字段int
。
避免使用像60
. SEC_PER_MIN
自记录代码。
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#define SEC_PER_DAY 86400
#define SEC_PER_HOUR 3600
#define SEC_PER_MIN 60
int main() {
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
printf("TimeZone-1 = %d\n", tz.tz_minuteswest);
printf("TimeZone-2 = %d\n", tz.tz_dsttime);
// Cast members as specific type of the members may be various
// signed integer types with Unix.
printf("TimeVal-3 = %lld\n", (long long) tv.tv_sec);
printf("TimeVal-4 = %lld\n", (long long) tv.tv_usec);
// Form the seconds of the day
long hms = tv.tv_sec % SEC_PER_DAY;
hms += tz.tz_dsttime * SEC_PER_HOUR;
hms -= tz.tz_minuteswest * SEC_PER_MIN;
// mod `hms` to insure in positive range of [0...SEC_PER_DAY)
hms = (hms + SEC_PER_DAY) % SEC_PER_DAY;
// Tear apart hms into h:m:s
int hour = hms / SEC_PER_HOUR;
int min = (hms % SEC_PER_HOUR) / SEC_PER_MIN;
int sec = (hms % SEC_PER_HOUR) % SEC_PER_MIN; // or hms % SEC_PER_MIN
printf("Current local time: %d:%02d:%02d\n", hour, min, sec);
return 0;
}
输出样本
TimeZone-1 = 360
TimeZone-2 = 1
TimeVal-3 = 1493735463
TimeVal-4 = 525199
Current local time: 9:31:03