Time and date functions in C provide a way to work with time and date values in a program. These functions are part of the standard C library and can be used to perform a wide range of tasks, such as measuring elapsed time, calculating time differences, and formatting date and time strings.
1. `time()` function: The `time()` function returns the current time as the number of seconds elapsed since the Unix epoch (January 1, 1970). The function takes a pointer to a `time_t` variable as its argument, which is used to store the current time value.
For example, the following code retrieves the current time and stores it in a `time_t` variable:
time_t current_time; time(¤t_time);
2. `ctime()` function: The `ctime()` function converts a `time_t` value to a string representation of the local time in the format “Day Month Date Hours:Minutes:Seconds Year\n”. The function takes a pointer to a `time_t` variable as its argument, and returns a pointer to a null-terminated string containing the formatted time value.
For example, the following code retrieves the current time and formats it as a string:
time_t current_time; time(¤t_time); char* formatted_time = ctime(¤t_time);
3. `gmtime()` and `localtime()` functions: The `gmtime()` and `localtime()` functions convert a `time_t` value to a `struct tm` structure representing the corresponding time in either UTC or local time, respectively. The `struct tm` structure contains fields for the year, month, day, hour, minute, second, and other time-related values.
For example, the following code retrieves the current time as a `struct tm` structure representing the local time:
time_t current_time; time(¤t_time); struct tm* local_time = localtime(¤t_time);
4. `strftime()` function: The `strftime()` function formats a `struct tm` structure as a string representation of the time, according to a specified format string. The format string can contain various placeholders for the different time-related values, such as %Y for the year, %m for the month, %d for the day, and so on.
For example, the following code formats a `struct tm` structure representing the current time as a string in the format “YYYY-MM-DD HH:MM:SS”:
time_t current_time; time(¤t_time); struct tm* local_time = localtime(¤t_time); char formatted_time[20]; strftime(formatted_time, 20, "%Y-%m-%d %H:%M:%S", local_time);
These are just a few examples of the time and date functions available in C. Other functions include `difftime()`, `mktime()`, and `asctime()`. By using these functions, programmers can perform a wide range of time and date-related tasks in their programs.