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(¤t_time); // call localtime() struct tm* local = localtime(¤t_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(¤t_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(¤t_time); printf("Local time and date: %s\n", asctime(local));
Recommended Post:
- What is the gmtime Function in C?
- difftime Function in C.
- Check date validity in C.
- C program to find the number of days in a month.
- Print a calendar for a given month for a year.
- C Programming Courses And Tutorials.
- CPP Programming Courses And Tutorials.
- Python Courses and Tutorials.
- Find the number of days between two given dates.
- Count of Leap Years in a given year range.
- Find the prime number using the C program.
- Using the C program to check valid date (date is valid or not)
- Check expiry date Using C program
- C program to print day name of week
- Convert number of days in terms of Years, Weeks and Days using C program
- C program to find century for a year.