🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The strftime() function in C is a standard library function that formats a struct tm time structure as a string according to a specified format. It is part of the C standard library (time.h). This function is useful for converting time data into human-readable strings in various formats.
Table of Contents
- Introduction
strftime()Function Syntax- Examples
- Formatting the Current Time as a String
- Using
strftime()with User Input
- Real-World Use Case
- Conclusion
Introduction
The strftime() function formats the components of a struct tm time structure into a string according to a format string. This function is highly versatile and allows for various date and time representations.
strftime() Function Syntax
The syntax for the strftime() function is as follows:
#include <time.h>
size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);
Parameters:
s: Pointer to the destination array where the resulting C-string is stored.max: Maximum number of characters to be written to the array, including the null terminator.format: C-string containing any combination of regular characters and special format specifiers.tm: Pointer to astruct tmthat contains the time information to be formatted.
Returns:
- The function returns the number of characters placed in the array
s, not including the null terminator. If the total number of characters, including the null terminator, exceedsmax, the function returns 0 and the contents ofsare indeterminate.
Examples
Formatting the Current Time as a String
To demonstrate how to use strftime() to format the current time as a string, we will write a simple program that retrieves the current time, converts it to a struct tm, and formats it.
Example
#include <stdio.h>
#include <time.h>
int main() {
time_t current_time;
struct tm *local_time;
char buffer[80];
// Get the current time
current_time = time(NULL);
// Convert the time to local time
local_time = localtime(¤t_time);
// Format the time as a string
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local_time);
// Print the result
printf("Formatted time: %s\n", buffer);
return 0;
}
Output:
Formatted time: 2023-07-04 12:34:56
Using strftime() with User Input
This example shows how to use strftime() to format a user-provided date and time as a string.
Example
#include <stdio.h>
#include <time.h>
int main() {
struct tm time_struct = {0};
char buffer[80];
// Get user input for the date and time
printf("Enter year: ");
scanf("%d", &time_struct.tm_year);
time_struct.tm_year -= 1900; // Adjust year
printf("Enter month (1-12): ");
scanf("%d", &time_struct.tm_mon);
time_struct.tm_mon -= 1; // Adjust month
printf("Enter day of the month (1-31): ");
scanf("%d", &time_struct.tm_mday);
printf("Enter hour (0-23): ");
scanf("%d", &time_struct.tm_hour);
printf("Enter minute (0-59): ");
scanf("%d", &time_struct.tm_min);
printf("Enter second (0-59): ");
scanf("%d", &time_struct.tm_sec);
// Format the time as a string
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &time_struct);
// Print the result
printf("Formatted time: %s\n", buffer);
return 0;
}
Output (example user input year "2023", month "7", day "4", hour "12", minute "30", second "0"):
Enter year: 2023
Enter month (1-12): 7
Enter day of the month (1-31): 4
Enter hour (0-23): 12
Enter minute (0-59): 30
Enter second (0-59): 0
Formatted time: 2023-07-04 12:30:00
Real-World Use Case
Formatting Timestamps for Logging
In real-world applications, the strftime() function can be used to format timestamps for logging purposes, providing readable and consistent date and time representations.
Example: Logging with Formatted Timestamps
#include <stdio.h>
#include <time.h>
void log_event(const char *event) {
time_t current_time = time(NULL);
struct tm *local_time = localtime(¤t_time);
char buffer[80];
if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local_time)) {
printf("[%s] %s\n", buffer, event);
} else {
printf("Failed to format the time.\n");
}
}
int main() {
log_event("Program started");
// Simulate some processing
sleep(2);
log_event("Processing complete");
return 0;
}
Output:
[2023-07-04 12:34:56] Program started
[2023-07-04 12:34:58] Processing complete
Conclusion
The strftime() function is essential for formatting struct tm time structures as strings in C. It is useful in various applications, particularly in logging, time-stamping, and displaying the current time in a readable format. By using different format specifiers, strftime() can create versatile and human-readable representations of date and time.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment