C programming time.h function - struct tm *localtime(const time_t *timer)
The localtime()
function is a part of the standard C library and is declared in the <time.h>
header file. It is used to convert a time value of type time_t
(which represents the number of seconds since the Epoch) to a struct tm
representation, which provides a more human-readable format for representing the time.
However, localtime()
differs from gmtime()
in that it converts the time value to the local time zone of the system, rather than Coordinated Universal Time (UTC).
The function signature is:
struct tm *localtime(const time_t *timer);
The localtime()
function takes a single argument, a pointer to a time_t
variable that contains the time value to be converted. It returns a pointer to a struct tm
that contains the broken-down time representation of the input time value in the local time zone.
Here is an example usage of localtime()
:
#include <stdio.h> #include <time.h> int main() { time_t current_time; struct tm *time_info; // Get the current time time(¤t_time); // Convert the current time to a struct tm representation in local time time_info = localtime(¤t_time); // Print the time in a human-readable format printf("The current time is %d:%02d:%02d in the local time zone.\n", time_info->tm_hour, time_info->tm_min, time_info->tm_sec); return 0; }
In this example, the time()
function is used to get the current time, and localtime()
is used to convert the time to a struct tm
representation in the local time zone. The resulting struct tm
is then used to print the time in a human-readable format.
Note that localtime()
returns a pointer to a static internal struct tm
object, so it is not thread-safe. If you need to use the result of localtime()
in a multithreaded program, you should make a copy of the result before calling localtime()
again.