C 庫函數(shù) size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr) 根據(jù) format 中定義的格式化規(guī)則,格式化結(jié)構(gòu) timeptr 表示的時間,并把它存儲在 str 中。
下面是 strftime() 函數(shù)的聲明。
size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr)
| 說明符 | 替換為 | 示例 |
|---|---|---|
| %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 | 十進制數(shù)表示的月份(01-12) | 08 |
| %M | 分(00-59) | 55 |
| %p | AM 或 PM 名稱 | PM |
| %S | 秒(00-61) | 02 |
| %U | 一年中的第幾周,以第一個星期日作為第一周的第一天(00-53) | 33 |
| %w | 十進制數(shù)表示的星期幾,星期日表示為 0(0-6) | 4 |
| %W | 一年中的第幾周,以第一個星期一作為第一周的第一天(00-53) | 34 |
| %x | 日期表示法 | 08/19/12 |
| %X | 時間表示法 | 02:50:06 |
| %y | 年份,最后兩個數(shù)字(00-99) | 01 |
| %Y | 年份 | 2012 |
| %Z | 時區(qū)的名稱或縮寫 | CDT |
| %% | 一個 % 符號 | % |
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 起的年數(shù) */
int tm_wday; /* 一周中的第幾天,范圍從 0 到 6 */
int tm_yday; /* 一年中的第幾天,范圍從 0 到 365 */
int tm_isdst; /* 夏令時 */
};
如果產(chǎn)生的 C 字符串小于 size 個字符(包括空結(jié)束字符),則會返回復(fù)制到 str 中的字符總數(shù)(不包括空結(jié)束字符),否則返回零。
下面的示例演示了 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, "%Y-%m-%d %H:%M:%S", info);
printf("格式化的日期 & 時間 : |%s|\n", buffer );
return(0);
}讓我們編譯并運行上面的程序,這將產(chǎn)生以下結(jié)果:
格式化的日期 & 時間 : |2018-09-19 08:59:07|