strftime() 是 C 语言中的一个函数,用于格式化日期和时间。它位于头文件 time.h 下,其中还包含一个名为 struct tm 的结构,用于保存时间和日期。strftime() 的语法如下所示:
strftime() 函数根据 format 中指定的格式化规则对分解的时间 tm 进行格式化,并将其存储在字符数组 s 中。
strftime() 的一些格式说明符如下所示:
%x = 首选日期表示
%I = 作为十进制数的小时(12 小时制)。
%M = 十进制的分钟数,范围从 00 到 59。
%p = 根据给定的时间值选择“AM”或“PM”等。
%a = 缩写的工作日名称
%^a = 大写字母缩写的工作日名称
%A = 完整的工作日名称
%b = 缩写月份名称
%^b = 大写字母缩写月份名称
%B = 完整月份名称 March
%c = 日期和时间表示
%d = 月份中的日期 (01-31)
%H = 24h 格式的小时 (00-23)
%I = 12 小时格式的小时 (01-12)
%j = 一年中的某一天 (001-366)
%m = 十进制数形式的月份 (01-12)
%M = 分钟 (00-59)
结构 struct tm 定义在time.h 如下:
size_t strftime(char *s, size_t max, const char *format,
const struct tm *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 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 : %sn", MY_TIME );
return(0);
}
Formatted date & time : 03/20/17 - 02:55PM为什么以及何时使用 strftime() ? 当我们制作一个软件/应用程序时,它将根据用户的需求以多种不同的格式输出当前时间和最重要的时间。那么在这种情况下,我们将使用这个函数。它的特点是我们可以以多种不同的格式显示日期和时间。