C 庫 - localtime() 函式



C 庫的 localtime() 函式用於處理與時間相關的任務,尤其是在使用者希望以人類可讀的格式顯示時間資訊時。

這裡,struct tm *localtime(const time_t *timer) 使用 timer 指向的時間來填充一個 tm 結構,該結構包含表示對應本地時間的數值。timer 的值被分解到 tm 結構中,並以本地時區表示。

語法

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

struct tm *localtime(const time_t *timer)

引數

此函式僅接受一個引數:

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

返回值

此函式返回一個指向 tm 結構的指標,其中填充了時間資訊。

以下是 tm 結構的資訊:

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 庫程式,用於演示 localtime() 函式。

#include <stdio.h>
#include <time.h>
int main () {        
   time_t rawtime;
   struct tm *info;
   time( &rawtime );
   info = localtime( &rawtime );
   printf("Current local time and date: %s", asctime(info));
   return(0);
}

輸出

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

Current local time and date: Tue May 14 10:01:48 2024

示例 2

下面的程式說明了如何使用 time() 函式獲取當前時間,以及如何使用 localtime() 函式顯示結果。

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

int main()
{
   time_t current_time;
   
   // get the current time using time()
   current_time = time(NULL);
   
   // call the function localtime() that takes timestamp and convert it into localtime representation
   struct tm *tm_local = localtime(&current_time);
   
   // corresponding component of the local time
   printf("Current local time : %d:%d:%d", tm_local -> tm_hour, tm_local -> tm_min, tm_local -> tm_sec);
   return 0;
} 

輸出

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

Current local time : 11:36:56

示例 3

在處理當前日期的任務時,它使用 localtime() 提供日期,並使用 strftime() 顯示格式化的結果。

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

int main(void) {
   size_t maxsize = 80;
   char dest[maxsize];

   time_t now;
   struct tm *tm_struct;

   time(&now);
   tm_struct = localtime(&now);

   strftime(dest, maxsize, "%D", tm_struct);
   printf("Current date: %s\n", dest);

   return 0;
}

輸出

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

Current date: 05/17/24
廣告