localtime() Function Example in C Programming

In this source code example, we will see how to use the localtime() function in C programming with an example.

localtime() Function Overview

The localtime() function in C is used to convert a given time from time_t format to a structure representing local time. This structure is of the type struct tm and includes details such as year, month, day, hour, minute, and second. The function resides in the time.h library. 

Key Points: 

- time.h header is required to utilize localtime()

- The function takes a pointer to a time_t object as its argument. 

- It returns a pointer to a struct tm which has the local time representation of the given time. 

- The time is adjusted according to the system's time zone settings.

Source Code Example

#include <stdio.h>
#include <time.h>  // Required for localtime(), time(), and struct tm

int main() {
    time_t current_time;
    struct tm *local_time_info;

    // Get the current calendar time
    time(&current_time);

    // Convert the current time to local time format
    local_time_info = localtime(&current_time);

    printf("The current local time is: %d-%d-%d %02d:%02d:%02d\n",
           local_time_info->tm_year + 1900,   // Years since 1900
           local_time_info->tm_mon + 1,       // Months are represented from 0 to 11
           local_time_info->tm_mday,          // Day of the month
           local_time_info->tm_hour,
           local_time_info->tm_min,
           local_time_info->tm_sec);

    return 0;
}

Output

The current local time is: YYYY-MM-DD HH:MM:SS
(Note: YYYY-MM-DD HH:MM:SS represents the current local time when the program is executed.)

Explanation

1. We include the essential header files: stdio.h for input/output operations and time.h for localtime(), time(), and the struct tm definition.

2. Within the main() function, we first capture the current calendar time in time_t format.

3. The localtime() function is used to convert this time_t value to a local time structure.

4. The structure fields, like tm_year, tm_mon, etc., are accessed to print the detailed date and time. Note that some adjustments are needed, such as adding 1900 to the year or adding 1 to the month, due to the way they are represented in the structure.

localtime() is an invaluable function when you want to interpret a timestamp in terms of the local time zone and components.


Comments