C localtime()

The localtime() function is defined in the time.h header file. This function helps to return the localtime. By using the time pointed by the argument 'timer' to fill a structure 'tm' with values that represent the local time.


struct tm *localtime(const time_t *timer); #where timer should be a pointer

 

localtime() Parameters: 

The localtime() function takes a single parameter 'timer' which is a pointer to the structure which contains a calendar time.

Parameter Description Required / Optional
timer pointer to a time_t value representing a calendar time Required

localtime() Return Value

The function returns a pointer to the structure 'tm' which contains the time information. The 'tm' structure information containing as following,


struct tm {
   int tm_sec;         /* seconds,  range 0 to 59          */
   int tm_min;         /* minutes, range 0 to 59           */
   int tm_hour;        /* hours, range 0 to 23             */
   int tm_mday;        /* day of the month, range 1 to 31  */
   int tm_mon;         /* month, range 0 to 11             */
   int tm_year;        /* The number of years since 1900   */
   int tm_wday;        /* day of the week, range 0 to 6    */
   int tm_yday;        /* day in the year, range 0 to 365  */
   int tm_isdst;       /* daylight saving time             */
};

Input Return Value
if parameter pointer to a struct tm object
if fails NULL pointer

 

Examples of localtime()

Example 1: Working of localtime() function in C?




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

int main()
{
   time_t rtime;
   struct tm *ltime;
   time( &rtime );
   ltime = localtime( &rtime );
   printf("Present local time & date is: %s", asctime(ltime));
   return(0);
}

Output:


Present local time & date is: Thu Aug 23 08:10:04 2012

Example 2: How localtime() works in C?


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

int main (){

    struct tm* localtm;
    time_t ts = time(NULL);
  
    // Get the localtime
    localtm = localtime(&ts);
  
    printf("The local time and date is: %s\n",
           asctime(localtm));
  
    return 0;
}

Output:


The local time and date is: Mon Sep 23 05:15:51 2019