localtime function in C?

The localtime function in C converts the calendar time pointed to by the timer into a broken-down time, expressed as local time. The localtime function is present in the <time.h> header file.

 

Syntax of localtime:

The prototype of the localtime () function is below:

#include <time.h>

struct tm *localtime(const time_t *timer);

 

Parameters:

The localtime function takes one parameter.

timer = Pointer to a time_t object to convert.

 

Returns:

The localtime functions return a pointer to the broken-down time, or a null pointer if the specified time cannot be converted to local time.

On Success:  The localtime() function returns a pointer to a tm object.
On Failure:  A null pointer is returned.

Note: In localtime() result is stored in a static internal tm object.

 

Example Program:

The below code explains how the localtime() function works in C.

#include <stdio.h>
#include <time.h>

int main()
{
    // object
    time_t current_time;

    // use time function
    time(&current_time);

    // call localtime()
    struct tm* local = localtime(&current_time);

    printf("Local time and date: %s\n",
           asctime(local));

    return 0;
}

Output:

Local time and date: Tue Jan 17 23:02:26 2023

 

How does the above code work?

In the above code, created one time_t object to store the times. When the program starts execution, the time() function stores the current time in the current_time variable.

// object
time_t current_time;

// use time function
time(&current_time);

 

Now in the last call, the localtime() function store the broken-down time into a pointer to the tm object.

// call gmtime()
struct tm* local = localtime(&current_time);

printf("Local time and date: %s\n",
       asctime(local));

 

Recommended Post:

Leave a Reply

Your email address will not be published. Required fields are marked *