localtime_r与gmtime_r

发布时间 2023-11-13 14:09:43作者: orange-C

简单说

gmtime_r转换与时区没关系,为UTC时间;

localtime_r与时区相关,为本地时间。

好记性不如烂笔头,记录一下。

 

参考:https://www.python100.com/html/115143.html

localtime_r函数的实现原理是基于时区的概念,它通过读取系统的时区文件来进行时区的转换。时区文件存放在目录"/usr/share/zoneinfo"下面,Linux系统中默认采用UTC时区,时区文件相对的路径是"/usr/share/zoneinfo/UTC"。

localtime_r函数会读取时区文件,从而获取本地时区的偏移量,将时间戳加上该偏移量就可以得到本地时间。具体实现可以参考下面的代码:

struct tm *localtime_r(const time_t *timep, struct tm *result)
{
    time_t time = *timep;
    struct tm *tmp;

    tmp = gmtime_r(&time, result);
    if (tmp == NULL)
        return NULL;

    time -= timezone;
    tmp = gmtime_r(&time, result);
    if (tmp == NULL)
        return NULL;

    result->tm_isdst = -1;
    return result;
}

 函数首先调用gmtime_r函数将时间戳转换为UTC时间,然后将UTC时间减去时区偏移量得到本地时间,并再次调用gmtime_r函数将本地时间转化为时间结构体。