localtime, localtime_s

< c‎ | chrono
Defined in header <time.h>
struct tm *localtime( const time_t *time );
struct tm *localtime_s(const time_t *restrict time, struct tm *restrict result);
(2) (since C11)
1) Converts given time since epoch (a time_t value pointed to by time) into calendar time, expressed in local time, in the struct tm format. The result is stored in static storage and a pointer to that static storage is returned.
2) Same as (1), except that the function uses user-provided storage result for the result and that the following errors are detected at runtime and call the currently installed constraint handler function:
  • time or result is a null pointer
As with all bounds-checked functions, localtime_s is only guaranteed to be available if __STDC_LIB_EXT1__ is defined by the implementation and if the user defines __STDC_WANT_LIB_EXT1__ to the integer constant 1 before including time.h.


[edit] Parameters

time - pointer to a time_t object to convert
result - pointer to a struct tm object to store the result

[edit] Return value

1) pointer to a static internal tm object on success, or null pointer otherwise. The structure may be shared between gmtime, localtime, and ctime and may be overwritten on each invocation.
2) copy of the result pointer, or null pointer on error (which may be a runtime constraint violation or a failure to convert the specified time to local calendar time)

[edit] Notes

This function localtime may not be thread-safe.

POSIX requires that this function sets errno to EOVERFLOW if it fails because the argument is too large.

POSIX defines a thread-safe alternative localtime_r, which is similar to the C11 function localtime_s, except that it does not check the validity of its input parameters.

[edit] Example

#define __STDC_WANT_LIB_EXT1__ 1
#include <time.h>
#include <stdio.h>
int main(void)
    time_t t = time(NULL);
    printf("UTC:   %s", asctime(gmtime(&t)));
    printf("local: %s", asctime(localtime(&t)));
#ifdef __STDC_LIB_EXT1__
    struct tm buf;
    char str[26];
    asctime_s(str,sizeof str,gmtime_s(&t, &buf));
    printf("UTC:   %s", str);
    asctime_s(str,sizeof str,localtime_s(&t, &buf)));
    printf("local: %s", str);


UTC:   Tue Feb 17 18:12:09 2015
local: Tue Feb 17 13:12:09 2015
UTC:   Tue Feb 17 18:12:09 2015
local: Tue Feb 17 13:12:09 2015

[edit] References

  • C11 standard (ISO/IEC 9899:2011):
  • The localtime function (p: 394)
  • K. The localtime_s function (p: 627)
  • C99 standard (ISO/IEC 9899:1999):
  • The localtime function (p: 343)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • The localtime function

[edit] See also

converts time since epoch to calendar time expressed as Coordinated Universal Time (UTC)
(function) [edit]
C++ documentation for localtime