時間編程碰到的一個問題

今天學習了關於時間上的編程,其中涉及了幾個主要的函數

首先時間可以分爲2種

1 是格林威治時間  這就是全球的標準時間

2 是日曆時間          所謂日曆時間就是從1970年1月1號00:00:00開始到現在這個時間之間的秒數

time_t time(time_t *tloc)

這個函數是用來獲得是日曆事件,這裏的tloc是用來存儲日曆事件的,如果tloc = null的話就不存儲時間,但是該函數還是會返回一個日曆事件的


struct tm* gmtime(const time_t * timep);

struct tm*localtime(const time_t *timep);

這兩個函數是用來將日曆時間轉化爲GMT時間或者是當地時間的

struct tm  是一個結構體,裏面包含了一些元素.

版本1

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

int main()
{
    typedef struct tm mytime;
    mytime * local;
    mytime * gmt;
    time_t rili = time(NULL);
    gmt = gmtime(&rili);
    printf("GMT is %d year %d month %d day %d hour\n",gmt->tm_year + 1900,gmt->tm_mon + 1,gmt->tm_mday,gmt->tm_hour);
    local = localtime(&rili);
    printf("Localtime is %d year %d month %d day %d hour\n",local->tm_year + 1900,local->tm_mon + 1,local->tm_mday,local->tm_hour);
    return 0;
}


版本2

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

int main()
{
    typedef struct tm mytime;
    mytime * local;
    mytime * gmt;
    time_t rili = time(NULL);
    gmt = gmtime(&rili);
    local = localtime(&rili);
    printf("GMT is %d year %d month %d day %d hour\n",gmt->tm_year + 1900,gmt->tm_mon + 1,gmt->tm_mday,gmt->tm_hour);

    printf("Localtime is %d year %d month %d day %d hour\n",local->tm_year + 1900,local->tm_mon + 1,local->tm_mday,local->tm_hour);
    return 0;
}


區別在於

gmt = gmtime(&rili);
local = localtime(&rili);
版本1中是取得一個時間以後就直接輸出,而版本2是先都取得了時間,在輸出。可是版本2 的結果是錯誤的,結果是GMT和localtime的時間是一模一樣了.

後來看了幫助文檔發現了這麼一句話

The gmtime, mktime, and localtime functions use the same single, statically allocated structure to hold their results. Each call to one of these functions destroys the result of any previous call. 


大概意思好像說是這三個函數相同的靜態的結構體來存儲結果,每一次調用函數都會破壞前面的結果。

所以我知道我的錯誤出現在哪裏了....



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章