Latest web development tutorials

C library functions - strftime ()

C standard library - <time.h> C standard library - <time.h>

description

Time C library functionsize_t strftime (char * str, size_t maxsize, const char * format, const struct tm * timeptr) formataccording to the formatting rules defined in the formatting structuretimeptrrepresented, and stores it instr.

statement

The following is a statement strftime () function.

size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr)

parameter

  • str - This is an array of pointers to the target, generated C to copy the string.
  • maxsize - This is the maximum number of characters to be copied to the str.
  • format - This is a C string containing any combination of normal characters and special format specifiers.The format specifier is replaced by the corresponding value is a function tm specified time. Format specifiers are:
说明符替换为实例
%a缩写的星期几名称 Sun
%A完整的星期几名称 Sunday
%b缩写的月份名称 Mar
%B完整的月份名称 March
%c日期和时间表示法 Sun Aug 19 02:56:02 2012
%d一月中的第几天(01-31)19
%H24 小时格式的小时(00-23)14
%I12 小时格式的小时(01-12)05
%j一年中的第几天(001-366)231
%m十进制数表示的月份(01-12)08
%M分(00-59)55
%pAM 或 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 - This is a pointer to a tm structure, the structure contains a chant broken down into the following sections of the calendar time:

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;       /* 夏令时						*/	
};

return value

If the produce is less than the size of the C string of characters (including the null terminator character), it returns to the copy number of characters in str (not including the null terminator character), otherwise it returns zero.

Examples

The following example demonstrates the strftime () function is used.

#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("格式化的日期 & 时间 : |%s|\n", buffer );
  
   return(0);
}

Let's compile and run the above program, which will result in the following:

格式化的日期 & 时间 : |08/23/12 - 12:40AM|

C standard library - <time.h> C standard library - <time.h>