
- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
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(¤t_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
廣告