The localtime_s
function converts the time value stored in time_t
and stores it in tm
structure. It also corrects the value for the local time zone. To use this function, thetime.h
header file needs to be included as shown below:
#include <time.h>
The localtime_s
function is written as shown below:
struct tm *localtime_s( const time_t *restrict timer, struct tm *restrict buff );
The Restrict keyword is used as a type qualifier for pointers, in pointer declarations, in code. It does not add any new functionalities.
This function takes two arguments:
timer
- pointer to a time_t
object that we are converting.buff
-pointer to a struct tm
object that stores the result. Buff is user provided storage.The function returns zero is it is successfully executed. Otherwise, it returns the respective error code.
timer | sourceTime | Return Value | Value in timer |
---|---|---|---|
NULL | any value | EINVAL | Not modified |
Not NULL | NULL | EINVAL | All fields set to -1 |
Not NULL | less than 0 or greater than _MAX__TIME64_T | EINVAL | All fields set to -1 |
EINVAL is a type of error value that means invalid argument.
The following code shows the how the localtime_s
function is used. The time
function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. timer
is passed to the localtime_s
function. The return value of localtime_s
is then passed to the asctime_s
function, which converts calendar time into its textual representation:
#define __STDC_WANT_LIB_EXT1__ 1#include <stdio.h>#include <time.h>int main(void){time_t timer = time(NULL);printf("Pakistan: %s", asctime(localtime(&timer)));#ifdef __STDC_LIB_EXT1__struct tm buff;char str[26];asctime_s(str,sizeof str,localtime_s(&timer, &buff));printf("Pakistan: %s", str);#endif}
Free Resources