strftime()是C语言中的一个函数,用于格式化日期和时间。它位于头文件time下。h、 它还包含一个名为struct tm的结构,用于保存时间和日期。strftime()的语法如下所示:
size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);
函数的作用是:根据format中指定的格式化规则格式化分解的time tm,并将其存储在字符数组s中。 strftime()的一些格式说明符如下所示: %x=首选日期表示法 %I=十进制的小时数(12小时时钟)。 %M=小数点后的分钟数,从00到59。 %p=根据给定时间值的“AM”或“PM”,等等。 %a=缩写的工作日名称
%^a=大写字母缩写的工作日名称 %A=完整的工作日名称 %b=缩写月份名称
%^b=大写字母缩写的月份名称 %B=月份全名 %c=日期和时间表示法 %d=月日(01-31) %H=24小时格式的小时数(00-23) %I=12小时格式的小时数(01-12) %j=一年中的某一天(001-366) %m=以十进制数字表示的月份(01-12) %M=分钟(00-59) Structure tm是在时间上定义的。h如下:
struct tm { int tm_sec; // seconds int tm_min; // minutes int tm_hour; // hours int tm_mday; // day of the month int tm_mon; // month int tm_year; // The number of years since 1900 int tm_wday; // day of the week int tm_yday; // day in the year int tm_isdst; // daylight saving time };
C
// C program to demonstrate the // working of strftime() #include <stdlib.h> #include <stdio.h> #include <time.h> #define Size 50 int main () { time_t t ; struct tm *tmp ; char MY_TIME[Size]; time ( &t ); //localtime() uses the time pointed by t , // to fill a tm structure with the // values that represent the // corresponding local time. tmp = localtime ( &t ); // using strftime to display time strftime (MY_TIME, sizeof (MY_TIME), "%x - %I:%M%p" , tmp); printf ( "Formatted date & time : %s" , MY_TIME ); return (0); } |
Formatted date & time : 03/20/17 - 02:55PM
为什么以及何时使用strftime()?
当我们制作一个软件/应用程序时,它将根据用户的需求以多种不同的格式输出当前时间和最重要的时间。那么在这种情况下,我们将使用这个函数。它的特点是,我们可以在很多地方显示日期和时间 不同的 格式。 参考: http://man7.org/linux/man-pages/man3/strftime.3.html>Linux手册页 本文由马扎尔·伊玛姆·汗撰稿。如果你喜欢Geeksforgek,并且想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。