C庫函數(shù) size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr) 格式表示的時間結(jié)構(gòu)timeptr根據(jù)定義格式并存儲到str格式規(guī)則。
以下是strftime() 函數(shù)的聲明。
size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr)
str -- 這是C字符串復(fù)制到目標(biāo)數(shù)組的指針。
maxsize -- 這是給 str 要復(fù)制的字符的最大數(shù)目。
format -- 這是C字符串,其中包含常規(guī)字符和特殊格式說明符的任意組合。這些格式說明符該函數(shù)相應(yīng)的值代替 tm 中指定的時間來表示。格式說明符:
| 指示符 | 取代 | 例子 |
|---|---|---|
| %a | Abbreviated weekday name | Sun |
| %A | Full weekday name | Sunday |
| %b | Abbreviated month name | Mar |
| %B | Full month name | March |
| %c | Date and time representation | Sun Aug 19 02:56:02 2012 |
| %d | Day of the month (01-31) | 19 |
| %H | Hour in 24h format (00-23) | 14 |
| %I | Hour in 12h format (01-12) | 05 |
| %j | Day of the year (001-366) | 231 |
| %m | Month as a decimal number (01-12) | 08 |
| %M | Minute (00-59) | 55 |
| %p | AM or PM designation | PM |
| %S | Second (00-61) | 02 |
| %U | Week number with the first Sunday as the first day of week one (00-53) | 33 |
| %w | Weekday as a decimal number with Sunday as 0 (0-6) | 4 |
| %W | Week number with the first Monday as the first day of week one (00-53) | 34 |
| %x | Date representation | 08/19/12 |
| %X | Time representation | 02:50:06 |
| %y | Year, last two digits (00-99) | 01 |
| %Y | Year | 2012 |
| %Z | Timezone name or abbreviation | CDT |
| %% | A % sign | % |
timeptr -- 這是為tm結(jié)構(gòu)的指針,它包含一個日歷時間分解成其組成部分,如下圖所示:
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字符串適合大小的字符(包括終止空字符)小于總數(shù)的字符復(fù)制到 str(不包括終止空字符),否則返回0。
下面的例子演示了如何使用strftime() 函數(shù)。
#include <stdio.h> #include <time.h> int main () { time_t rawtime; struct tm *info; char buffer[80]; time( &rawtime ); info = localtime( &rawtime ); strftime(buffer,80,"%x - %I:%M%p", info); printf("Formatted date & time : |%s| ", buffer ); return(0); }
讓我們編譯和運(yùn)行上面的程序,這將產(chǎn)生以下結(jié)果:
Formatted date & time : |08/23/12 - 12:40AM|