localtime_r与gmtime_r

简单说

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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函数将本地时间转化为时间结构体。

 

posted on   orange-C  阅读(892)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示