天天看點

活用LINUX時間函數

        前幾天同僚聯系我說通過localtime得到的時間總比系統時間少8個小時,于是立刻引起我的警覺。首先想到的就是時區問題,因為相差一個時區就相差一個小時,我們的中原標準時間屬于東八區,比格林威治時間整整多8小時。

活用LINUX時間函數

       首先分析代碼,我的同僚代碼先用time(&timep);然後調用asctime(gmtime(&timep))得到它的格林威治時間。但localtime連結的是我國的上海時區。

       [[email protected] ~]$ ls -l /etc/localtime

lrwxrwxrwx. 1 root root 35 Aug 15  2018 /etc/localtime -> ../usr/share/zoneinfo/Asia/Shanghai    

活用LINUX時間函數

是以如果想讓gmtime(&timep)的時間和用指令date擷取的時間相等,那麼可以将localtime的軟連結改成UTC,那麼gmtime時間和date時間相等。

[[email protected] ~]$ ls -l /etc/localtime

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

活用LINUX時間函數

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;
}
           

繼續閱讀