struct tm 🎯Welcome to our comprehensive guide on the struct tm in C programming! This tutorial is designed to help both beginners and intermediates understand this powerful tool. 📝 struct tm is a predefined structure in the C standard library used to represent date and time values. Let's dive in!
In this lesson, we'll explore the struct tm structure, its composition, and how to use it to manipulate date and time. We'll also discuss real-world applications of this structure.
struct tm 💡A struct tm structure consists of the following fields:
tm_sec: seconds after the minute (0-60)tm_min: minutes past the hour (0-59)tm_hour: hours since midnight (0-23)tm_mday: day of the month (1-31)tm_mon: months since January (0-11)tm_year: years since 1900tm_wday: days since Sunday (0-6, Sunday=0)tm_yday: days since January 1 (1-365 or 366)struct tm 💡To create and initialize a struct tm, you can use the following syntax:
struct tm my_date = {
0, // tm_sec
0, // tm_min
0, // tm_hour
1, // tm_mday
1, // tm_mon
2022, // tm_year
0, // tm_wday
1, // tm_yday
0 // tm_isdst (Daylight Saving Time flag)
};struct tm 💡The C standard library provides several functions to manipulate the struct tm. Here are two examples:
localtime(): This function converts the current time (as a time_t value) to a struct tm.time_t current_time = time(NULL);
struct tm *curr_tm = localtime(¤t_time);mktime(): This function creates a struct tm representing a given date and time. If the time is invalid, mktime() adjusts it to the nearest valid time.struct tm my_birthday = {
.tm_mday = 15,
.tm_mon = 6,
.tm_year = 1990
};
time_t my_birthday_time = mktime(&my_birthday);struct tm is essential in various real-world projects, such as logging events, date calculations, and even creating simple calendar applications.
What does the `tm_wday` field in a `struct tm` represent?
Stay tuned for more on C programming! 🚀 In the next lesson, we'll discuss how to work with dates and times using struct tm. See you there! 👋