Strftime() in C

Introduction:

The time.h header file contains a definition for the strftime function. Its purpose is to generate and save a string in the specified format. It makes use of the time values kept in a specific tm struct.

Syntax

The syntax for the strftime() method is provided below.

The parameters or arguments used:

Str-

It is a pointer to the target array where the copied C string from the result is stored.

Maxsize −

It is the maximum character count that can be copied to str.

Format −

It is the C string that can contain any mixture of alphabetic and numeric characters as well as unique format specifiers. The function replaces these format specifiers with the correct values to represent the time supplied in tm.

These are the format specifiers:

SpecifierReplaced byExample
%aWeekday's abbreviated nameMon
%AWeekday's full nameMonday
%bShortened month nameFeb
%BMonth's full nameFebruary
%cDisplay of time and dateSun Aug 19 02:56:02 2012
%d(01-31) Day of the month19
%HHour (00-23) in 24-hour format14
%I(01-12) hour in a 12-hour format05
%jDate (from 001 to 366)231
%mMonth expressed as a decimal (01-12)08
%M(Minute 00:59)55
%pAM or PM time zonePM
%S(00-61)second02
%UWeek number, with the first Sunday serving as week one's first day (00-53)33
%wSunday is represented by the number 0 (0-6) on a weekday.4
%WWeek number, with the first Monday serving as week one's first day (00-53)34
%xRepresenting dates08/19/12
%XRepresentation of time02:50:06
%yLast two digits of the year (00-99)01
%YYear2012
%ZName or shorthand for the time zoneCDT
%%A% symbol%

The timeptr -

It is a pointer to a tm structure that holds the components of a calendar time, as seen below.

Return Value

The total number of characters copied to str (excluding the ending null-character) is returned if the resulting C string can be written in fewer than size characters (which includes the terminating null-character), in which case zero is returned.

Example

The strftime() method is used in the example below.

Output:

The Formatted date & time is : |06/03/23 - 05:17PM|

Example:2

Output:

The Formatted date &time : 06/03/23 - 05:42PM

Explanation:

Here all the essential header files (stdlib.h, stdio.h, and time.h) are added. The size of the character array MY_TIME is defined by the Size constant, which will store the formatted date and time.

To obtain the current time in seconds since the Unix epoch (January 1, 1970), the time() function is used with the address of t as an argument. The address of t is passed as an argument when the localtime() method is called. The MY_TIME array contains the formatted date and time.

Using printf(), the formatted date and time are displayed on the terminal. The main() function comes to a close, and the program returns 0 to signify that it ran successfully.






Latest Courses