C 庫 - gmtime() 函式



C 庫的 gmtime() 函式,其型別為 struct,使用 timer 指向的值填充一個結構體 (tm),其中包含表示對應時間的數值,以協調世界時 (UTC) 或格林威治標準時間 (GMT) 時區表示。這對於日誌記錄、時間戳和排程等操作非常有用。

語法

以下是 C 庫 gmtime() 函式的語法:

struct tm *gmtime(const time_t *timer)

引數

此函式僅接受一個引數:

  • timeptr − 這是一個指向 time_t 值的指標,表示日曆時間。

返回值

此函式返回一個指向包含已填充時間資訊的 tm 結構體的指標。

以下是 timeptr 結構體的列表:

struct tm {
   int tm_sec;         /* seconds,  range 0 to 59          */
   int tm_min;         /* minutes, range 0 to 59           */
   int tm_hour;        /* hours, range 0 to 23             */
   int tm_mday;        /* day of the month, range 1 to 31  */
   int tm_mon;         /* month, range 0 to 11             */
   int tm_year;        /* The number of years since 1900   */
   int tm_wday;        /* day of the week, range 0 to 6    */
   int tm_yday;        /* day in the year, range 0 to 365  */
   int tm_isdst;       /* daylight saving time             */	
};

示例 1

以下是一個基本的 C 庫程式,用於演示 gmtime() 函式。

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

#define BST (+1)
#define CCT (+8)

int main () {

   time_t rawtime;
   struct tm *info;

   time(&rawtime);
   /* Get GMT time */
   info = gmtime(&rawtime );
   
   printf("Current world clock:\n");
   printf("London : %2d:%02d\n", (info->tm_hour+BST)%24, info->tm_min);
   printf("China  : %2d:%02d\n", (info->tm_hour+CCT)%24, info->tm_min);

   return(0);
}

輸出

以上程式碼產生以下結果:

Current world clock:
London : 14:10
China : 21:10

示例 2

在這裡,我們使用 gmtime() 獲取當前本地時間,並列印不同國家/地區的本地時區。

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

#define CST (+8)
#define IND (-5)

int main() {
   time_t current_time;
   struct tm* ptime;

   time(&current_time);
   ptime = gmtime(&current_time);

   printf("Current time:\n");
   printf("Beijing (China): %02d:%02d:%02d\n", (ptime->tm_hour + CST) % 24, ptime->tm_min, ptime->tm_sec);
   printf("Delhi (India): %02d:%02d:%02d\n", (ptime->tm_hour + IND) % 24, ptime->tm_min, ptime->tm_sec);

   return 0;
}

輸出

執行以上程式碼後,我們得到以下結果:

Current time:
Beijing (China): 16:23:24
Delhi (India): 03:23:24

示例 3

gmtime() 函式演示瞭如何將當前日曆時間轉換為文字表示 (asctime_s())。

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <time.h>

int main(void) {
   struct tm tm = *gmtime(&(time_t){time(NULL)});

   printf("Current time (using asctime()): %s\n", asctime(&tm));

   #ifdef __STDC_LIB_EXT1__
   char str[50];
   asctime_s(str, sizeof str, &tm);
   printf("Current time (using asctime_s()): %s\n", str);
   #endif

   return 0;
}

輸出

執行以上程式碼後,我們得到以下結果:

Current time (using asctime()): Tue May 14 08:33:26 2024
廣告