C programming localtime time.h


In C programming the <time.h> localtime function convert the calendar time in to a broken down time expressed as local time:the time shown by your computer.The declaration of the function is given below.

struct tm *localtime(const time_t *timer);

Parameters:
timer -A time_t type variable that stores the calendar time.

Return type
struct tm -Returns a pointer to the broken-down time,or a null pointer if the specified time cannot be converted to local time.

The calendar time here simply means the number of seconds elapsed since 1st January 1900,so the ‘timer’ holds the number of seconds and the ‘localtime’ convert this seconds:numeric values,to local time which can later be converted to the form,

Tue Jun 16 01:03:52 1973\n\0

by calling the function ‘asctime’ using the returned value as the argument.To get the number of seconds elapsed call the function ‘time’.A code example is given below.

Code example

time_t t;

struct tm *tt;

time(&t); //get the number of seconds elapsed since 1st January 1900

tt=localtime(&t); //convert ‘t’ value to UTC

printf(“%s” , asctime(tt) ); //get the current UTC

Output,

Fri Jul 21 22:07:44 2017

The time and date outputted must be same as the date and time shown by your computer.Another way of getting the local time directly without calling the ‘localtime’ function is to call the ‘ctime’ function passing reference ‘t’ as the argument.A code example is given below.

Code example

time_t t;

struct tm *tt;

time(&t); //get the number of seconds elapsed since 1st January 1900

printf(“%s” , ctime(t) ); //get the local time

Output,

Fri Jul 21 22:07:44 2017

To get the UTC (or Greenwich Mean time) call the function ‘gmtime’.


Related links

->C ctime time.h

->C asctime time.h

->C time time.h

->C gmtime time.h