名稱空間
變體
操作

localtime, localtime_r, localtime_s

來自 cppreference.com
< c‎ | 時間
定義於標頭檔案 <time.h>
struct tm* localtime  ( const time_t* timer );
(1)
struct tm* localtime_r( const time_t* timer, struct tm* buf );
(2) (自 C23 起)
struct tm* localtime_s( const time_t* restrict timer, struct tm* restrict buf );
(3) (C11 起)
1) 將給定的自紀元以來的時間(一個指向 time_t 值的指標 timer)轉換為日曆時間,以本地時間表示,格式為 struct tm。結果儲存在靜態儲存區,並返回指向該靜態儲存區的指標。
2)(1) 相同,但函式使用使用者提供的儲存區 buf 來儲存結果。
3)(1) 相同,但函式使用使用者提供的儲存區 buf 來儲存結果,並且以下錯誤會在執行時被檢測到,並呼叫當前已安裝的 約束處理程式 函式:
  • timerbuf 是空指標
與所有邊界檢查函式一樣,localtime_s 僅在實現定義了 __STDC_LIB_EXT1__ 且使用者在包含 <time.h> 之前將 __STDC_WANT_LIB_EXT1__ 定義為整數常量 1 時才保證可用。

目錄

[編輯] 引數

timer - 指向要轉換的 time_t 物件的指標
buf - 指向 struct tm 物件以儲存結果的指標

[編輯] 返回值

1) 成功時,返回指向靜態內部 tm 物件的指標;否則返回空指標。該結構可能在 gmtimelocaltimectime 之間共享,並且在每次呼叫時可能被覆蓋。
2,3) 成功時,返回 buf 指標的副本;錯誤時(可能是執行時約束違例或無法將指定時間轉換為本地日曆時間)返回空指標。

[編輯] 注意

函式 localtime 可能不是執行緒安全的。

POSIX 要求如果 localtimelocaltime_r 因引數過大而失敗,則將 errno 設定為 EOVERFLOW

POSIX 指定 localtimelocaltime_r 的時區資訊由呼叫 tzset 來確定,後者讀取環境變數 TZ

Microsoft CRTlocaltime_s 的實現與 C 標準不相容,因為它引數順序相反且返回 errno_t

[編輯] 示例

#define __STDC_WANT_LIB_EXT1__ 1
#define _XOPEN_SOURCE // for putenv
#include <stdio.h>
#include <stdlib.h>   // for putenv
#include <time.h>
 
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
}

可能的輸出

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

[編輯] 參考文獻

  • C23 標準 (ISO/IEC 9899:2024)
  • 7.27.3.4 The localtime function (p: TBD)
  • K.3.8.2.4 The localtime_s function (p: TBD)
  • C17 標準 (ISO/IEC 9899:2018)
  • 7.27.3.4 The localtime function (p: 288)
  • K.3.8.2.4 The localtime_s function (p: 455)
  • C11 標準 (ISO/IEC 9899:2011)
  • 7.27.3.4 The localtime function (p: 394)
  • K.3.8.2.4 The localtime_s function (p: 627)
  • C99 標準 (ISO/IEC 9899:1999)
  • 7.23.3.4 The localtime function (p: 343)
  • C89/C90 標準 (ISO/IEC 9899:1990)
  • 4.12.3.4 The localtime function

[編輯] 參閱

將自紀元以來的時間轉換為協調世界時 (UTC) 表示的日曆時間
(function) [編輯]
C++ 文件 關於 localtime