📜  C / C++中的strftime()函数

📅  最后修改于: 2021-05-25 23:05:37             🧑  作者: Mango

strftime()是C语言中的函数,用于格式化日期和时间。它位于头文件time.h下,该文件还包含一个名为struct tm的结构,该结构用于保存时间和日期。 strftime()的语法如下所示:

size_t strftime(char *s, size_t max, const char *format, 
                                          const struct tm *tm); 

strftime()函数根据format中指定的格式化规则对分解时间tm进行格式化,并将其存储在字符数组s中。
strftime()的一些格式说明符如下所示:
%x =首选日期表示
%I =小时(十进制数字)(12小时制)。
%M =分钟的分钟数,范围从00到59。
%p =根据给定的时间值,是“ AM”还是“ PM”,等等。
%a =星期几的缩写

%^ a =大写字母的工作日缩写名称
%A =工作日全名
%b =缩写的月份名称

%^ b =大写字母的缩写月份名称
%B = 3月的全月名称
%c =日期和时间表示
%d =每月的一天(01-31)
%H = 24小时格式的小时(00-23)
%I = 12h格式的小时(01-12)
%j =一年中的某天(001-366)
%m =月作为十进制数字(01-12)
%M =分钟(00-59)
在time.h中定义的结构struct tm如下:

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 
#include 
#include 
#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\n", MY_TIME );
    return(0);
}


Formatted date & time : 03/20/17 - 02:55PM

为什么以及何时使用strftime()?

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。