C 庫函數 - strftime()
描述
C 庫函數 size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr) 根據 format 中定義的格式化規則,格式化結構 timeptr 表示的時間,並把它存儲在 str 中。
聲明
下面是 strftime() 函數的聲明。
size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr)
參數
- str -- 這是指向目標數組的指針,用來復制產生的 C 字符串。
- maxsize -- 這是被復制到 str 的最大字符數。
- format -- 這是 C 字符串,包含了普通字符和特殊格式說明符的任何組合。這些格式說明符由函數替換為表示 tm 中所指定時間的相對應值。格式說明符是:
說明符 | 替換為 | 實例 |
---|---|---|
%a | 縮寫的星期幾名稱 | Sun |
%A | 完整的星期幾名稱 | Sunday |
%b | 縮寫的月份名稱 | Mar |
%B | 完整的月份名稱 | March |
%c | 日期和時間表示法 | Sun Aug 19 02:56:02 2012 |
%d | 一月中的第幾天(01-31) | 19 |
%H | 24 小時格式的小時(00-23) | 14 |
%I | 12 小時格式的小時(01-12) | 05 |
%j | 一年中的第幾天(001-366) | 231 |
%m | 十進制數表示的月份(01-12) | 08 |
%M | 分(00-59) | 55 |
%p | AM 或 PM 名稱 | PM |
%S | 秒(00-61) | 02 |
%U | 一年中的第幾周,以第一個星期日作為第一周的第一天(00-53) | 33 |
%w | 十進制數表示的星期幾,星期日表示為 0(0-6) | 4 |
%W | 一年中的第幾周,以第一個星期一作為第一周的第一天(00-53) | 34 |
%x | 日期表示法 | 08/19/12 |
%X | 時間表示法 | 02:50:06 |
%y | 年份,最后兩個數字(00-99) | 01 |
%Y | 年份 | 2012 |
%Z | 時區的名稱或縮寫 | CDT |
%% | 一個 % 符號 | % |
- timeptr -- 這是指向 tm 結構的指針,該結構包含了一個唄分解為以下各部分的日歷時間:
struct tm { int tm_sec; /* 秒,范圍從 0 到 59 */ int tm_min; /* 分,范圍從 0 到 59 */ int tm_hour; /* 小時,范圍從 0 到 23 */ int tm_mday; /* 一月中的第幾天,范圍從 1 到 31 */ int tm_mon; /* 月份,范圍從 0 到 11 */ int tm_year; /* 自 1900 起的年數 */ int tm_wday; /* 一周中的第幾天,范圍從 0 到 6 */ int tm_yday; /* 一年中的第幾天,范圍從 0 到 365 */ int tm_isdst; /* 夏令時 */ };
返回值
如果產生的 C 字符串小於 size 個字符(包括空結束字符),則會返回復制到 str 中的字符總數(不包括空結束字符),否則返回零。
#include <stdio.h> #include <time.h> #include <windows.h> void timemy() {time_t curtime; time(&curtime); printf("Current time = %s", ctime(&curtime)); } void strftimemy() { time_t rawtime; struct tm *info; char buffer[80]; time( &rawtime ); info = localtime( &rawtime ); strftime(buffer, 80, "%Y-%m-%d %H:%M:%S %A", info); printf("format date & time : %s\n", buffer ); } int main () { timemy(); strftimemy(); /*for (int i = 0; i < 100; i++) { printf("%d\n",i); timemy(); Sleep(300); }*/ return(0); }
Current time = Sat Aug 29 22:46:17 2020 format date & time : 2020-08-29 22:46:17 Saturday