localtime, localtime_r, localtime_s
來自 cppreference.com
定義於標頭檔案 <time.h> |
||
(1) | ||
(2) | (自 C23 起) | |
(3) | (C11 起) | |
2) 與 (1) 相同,但函式使用使用者提供的儲存區 buf 來儲存結果。
3) 與 (1) 相同,但函式使用使用者提供的儲存區 buf 來儲存結果,並且以下錯誤會在執行時被檢測到,並呼叫當前已安裝的 約束處理程式 函式:
- timer 或 buf 是空指標
- 與所有邊界檢查函式一樣,
localtime_s
僅在實現定義了 __STDC_LIB_EXT1__ 且使用者在包含 <time.h> 之前將 __STDC_WANT_LIB_EXT1__ 定義為整數常量 1 時才保證可用。
目錄 |
[編輯] 引數
timer | - | 指向要轉換的 time_t 物件的指標 |
buf | - | 指向 struct tm 物件以儲存結果的指標 |
[編輯] 返回值
2,3) 成功時,返回 buf 指標的副本;錯誤時(可能是執行時約束違例或無法將指定時間轉換為本地日曆時間)返回空指標。
[編輯] 注意
函式 localtime
可能不是執行緒安全的。
POSIX 要求如果 localtime
和 localtime_r
因引數過大而失敗,則將 errno 設定為 EOVERFLOW。
POSIX 指定 localtime
和 localtime_r
的時區資訊由呼叫 tzset
來確定,後者讀取環境變數 TZ。
在 Microsoft CRT 中 localtime_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
[編輯] 參閱
(C23)(C11) |
將自紀元以來的時間轉換為協調世界時 (UTC) 表示的日曆時間 (function) |
C++ 文件 關於 localtime
|