
- 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庫 - asctime() 函式
C庫 asctime() 函式返回一個指向字串的指標,該字串表示結構體 struct timeptr 的日期和時間。此函式用於將日曆時間表示為人類可讀的字串。
語法
以下是C庫 asctime() 函式的語法:
char *asctime(const struct tm *timeptr)
引數
timeptr 是指向 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 */ };
返回值
此函式返回一個C字串,其中包含以人類可讀的格式 Www Mmm dd hh:mm:ss yyyy 表示的日期和時間資訊,其中 Www 是星期幾,Mmm 是月份的字母縮寫,dd 是月份中的第幾天,hh:mm:ss 是時間,yyyy 是年份。
示例1
以下是 asctime() 函式的簡單C庫程式。
#include <stdio.h> #include <string.h> #include <time.h> int main () { struct tm t; t.tm_sec = 10; t.tm_min = 10; t.tm_hour = 6; t.tm_mday = 25; t.tm_mon = 2; t.tm_year = 89; t.tm_wday = 6; puts(asctime(&t)); return(0); }
輸出
以上程式碼產生以下結果:
Sat Mar 25 06:10:10 1989
示例2
為了獲得當前/本地時間,我們使用 localtime() 函式生成時鐘的本地時間,然後呼叫 asctime() 函式來顯示它。
#include <stdio.h> #include <time.h> int main() { struct tm* ptr; time_t lt; lt = time(NULL); ptr = localtime(<); printf("Current local time: %s", asctime(ptr)); return 0; }
輸出
執行上述程式碼後,我們將得到以下結果:
Current local time: Tue May 14 07:00:11 2024
示例3
此C程式使用 asctime() 函式和(如果可用)asctime_s() 函式以人類可讀的格式顯示當前本地時間。
#define __STDC_WANT_LIB_EXT1__ 1 #include <stdio.h> #include <time.h> int main(void) { struct tm tm = *localtime(&(time_t){time(NULL)}); printf("Current local time (using asctime()): %s\n", asctime(&tm)); #ifdef __STDC_LIB_EXT1__ char str[50]; asctime_s(str, sizeof str, &tm); printf("Current local time (using asctime_s()): %s\n", str); #endif return 0; }
輸出
執行上述程式碼後,我們將得到以下結果:
Current local time (using asctime()): Tue May 14 07:09:57 2024
廣告