Welcome to the exciting world of C Programming! Today, we're going to dive deep into the strftime() function. This powerful tool will help you format and display dates and times in your C programs. Let's get started!
The strftime() function formats and writes date and time according to the format string into a character array. Here's a simple breakdown:
#include <stdio.h>
#include <time.h>
int main(void)
{
char date_time[20];
struct tm *now;
time_t now_time;
// Get current time
time(&now_time);
now = localtime(&now_time);
// Format current date and time
strftime(date_time, sizeof(date_time), "%Y-%m-%d %H:%M:%S", now);
printf("Current date and time: %s\n", date_time);
return 0;
}In this example, we first include the necessary headers for standard input/output and time manipulation. Then, we declare a character array date_time to store the formatted date and time, a struct tm pointer now to hold the current date and time data, and time_t variable now_time to store the current time in the system.
The localtime() function converts the current time in seconds (now_time) into a struct tm data structure. Next, we use strftime() to format the date and time data into the date_time array, following the format string "%Y-%m-%d %H:%M:%S". Finally, we print the formatted date and time to the console.
The format string of strftime() contains various directives to format date and time components. Here are some commonly used directives:
| Directive | Description |
|-----------|-----------------------------------------------------------------------------------------------------------------------------|
| %Y | Year with century as a decimal number (e.g., 2023) |
| %m | Month as a zero-padded decimal number (e.g., 01, 12) |
| %d | Day of the month as a zero-padded decimal number (e.g., 01, 31) |
| %H | Hour (24-hour clock) as a zero-padded decimal number (e.g., 00, 23) |
| %M | Minute as a zero-padded decimal number (e.g., 00, 59) |
| %S | Second as a zero-padded decimal number (e.g., 00, 59) |
| %a | Abbreviated weekday name (e.g., Sun, Mon, Tue, etc.) |
| %A | Full weekday name (e.g., Sunday, Monday, Tuesday, etc.) |
| %b | Abbreviated month name (e.g., Jan, Feb, Mar, etc.) |
| %B | Full month name (e.g., January, February, March, etc.) |
Let's create a simple clock that displays the current date and time every second:
#include <stdio.h>
#include <time.h>
int main(void)
{
char date_time[20];
struct tm *now;
time_t now_time;
while (1)
{
time(&now_time);
now = localtime(&now_time);
// Format current date and time
strftime(date_time, sizeof(date_time), "%Y-%m-%d %H:%M:%S", now);
printf("\rCurrent date and time: %s", date_time);
fflush(stdout);
sleep(1);
}
return 0;
}In this example, we use a while loop to repeatedly display the current date and time every second. The sleep(1) function call makes the program pause for one second before refreshing the output.
Which function converts the current time in seconds into a `struct tm` data structure in C?