linux 中 gmtime和 localtime區別


gmtime和localtime

struct tm *gmtime(const time_t *timep);
struct tm *gmtime_r(const time_t *timep, struct tm *result);

struct tm *localtime(const time_t *timep);
struct tm *localtime_r(const time_t *timep, struct tm *result);

 

參數都是time_t,the number of seconds elapsed since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).

但是gmtime 返回的 tm時間是UTC時區的時間。

localtime 返回得時間是系統設置的時區的時間。

 

有段代碼可以看一下

 

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{

time_t time;
struct tm tm;
struct tm *tm_ret;

tm.tm_year = 2020-1900;
tm.tm_mon = 9-1;
tm.tm_mday = 10;
tm.tm_hour = 16;
tm.tm_min = 30;
tm.tm_sec = 0;

time= mktime(&tm);

printf("time:%lld\n", time);

tm_ret = gmtime(&time);
printf("%d/%02d/%02d %02d:%02d:%02d\n", tm_ret->tm_year +1900, tm_ret->tm_mon +1, tm_ret->tm_mday, tm_ret->tm_hour, tm_ret->tm_min, tm_ret->tm_sec);

tm_ret = localtime(&time);
printf("%d/%02d/%02d %02d:%02d:%02d\n", tm_ret->tm_year +1900, tm_ret->tm_mon +1, tm_ret->tm_mday, tm_ret->tm_hour, tm_ret->tm_min, tm_ret->tm_sec);
return 0;
}

 

結果是:

time:1599726600
2020/09/10 08:30:00
2020/09/10 16:30:00




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM