linux系统时间编程(7) UTC秒数转为本地日历时间localtime函数

struct tm *localtime ( const time_t *timer ); (1)
struct tm *localtime_r( const time_t *timer, struct tm *buf ); (2) (since C23)
struct tm *localtime_s( const time_t *restrict timer, struct tm *restrict buf ); (3) (since C11)

功能和gmtime类似,将UTC秒数转为本地日历时间,而gmtime是转为UTC日历时间,即不带时区。

同样线程不安全。

#define __STDC_WANT_LIB_EXT1__ 1
#define _XOPEN_SOURCE // for putenv
#include 
#include 
#include    // for putenv
 
int main(void)
{
     
    time_t t = time(NULL);
    printf("UTC:       %s", asctime(gmtime(&t)));
    printf("local:     %s", asctime(localtime(&t)));
    // POSIX-specific
    putenv("TZ=Asia/Singapore");
    printf("Singapore: %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);
#endif
}

Possible output:

UTC: Fri Sep 15 14:22:05 2017
local: Fri Sep 15 14:22:05 2017
Singapore: Fri Sep 15 22:22:05 2017
UTC: Fri Sep 15 14:22:05 2017
local: Fri Sep 15 14:22:05 2017

你可能感兴趣的:(linux系统时间编程(7) UTC秒数转为本地日历时间localtime函数)