活用LINUX时间函数

        前几天同事联系我说通过localtime得到的时间总比系统时间少8个小时,于是立刻引起我的警觉。首先想到的就是时区问题,因为相差一个时区就相差一个小时,我们的北京时间属于东八区,比格林威治时间整整多8小时。

       

       首先分析代码,我的同事代码先用time(&timep);然后调用asctime(gmtime(&timep))得到它的格林威治时间。但localtime链接的是我国的上海时区。

       [testbep@system-2 ~]$ ls -l /etc/localtime
lrwxrwxrwx. 1 root root 35 Aug 15  2018 /etc/localtime -> ../usr/share/zoneinfo/Asia/Shanghai    

所以如果想让gmtime(&timep)的时间和用命令date获取的时间相等,那么可以将localtime的软链接改成UTC,那么gmtime时间和date时间相等。

[testbep@rg-smp112 ~]$ ls -l /etc/localtime
lrwxrwxrwx. 1 root root 23 Dec 14 05:38 /etc/localtime -> /usr/share/zoneinfo/UTC

lrwxrwxrwx. 1 root root 23 Dec 14 05:38 /etc/localtime -> /usr/share/zoneinfo/UTC

并附上测试代码:

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main()
{
   time_t timep;
   time(&timep);
   struct tm scf_tm;
   scf_tm=*localtime(&timep);
   printf("%s\n", asctime(gmtime(&timep)));
   printf("%d\n",scf_tm.tm_year + 1900);
   printf("%d\n",scf_tm.tm_mon);
   printf("%d\n",scf_tm.tm_mday);
   printf("%d\n",scf_tm.tm_hour);
   printf("%d\n",scf_tm.tm_min);
   printf("%d\n",scf_tm.tm_sec);
   return 0;
}

      

        

猜你喜欢

转载自blog.csdn.net/lzyzuixin/article/details/111167002